Rotate Array
LeetCode 189 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్త్రూ
Reverse all, reverse first k, reverse the rest.
నేను Rotate Array (LeetCode 189) ను ఇలా పరిష్కరించాను — Two Pointers ప్యాటర్న్లోని ఒక మధ్యస్థం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.
కింది వివరణ ఇంగ్లీష్లో ఉంది.
Intuition
Rotating right by k moves the last k elements to the front. Reverse the whole array (they're now at the front, but backwards), then reverse the first k and the rest separately to fix both halves.
Approach
- 1
Reduce k modulo n.
- 2
Reverse the entire array.
- 3
Reverse nums[0..k−1].
- 4
Reverse nums[k..n−1].
నేను ఎలా పరిష్కరించాను
Triple reversePythonO(n) time · O(1) space
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
def reverse_elements(nums,start,end):
while start<=end:
nums[start],nums[end]=nums[end],nums[start]
start+=1
end-=1
k = k%len(nums)
#reverse entire array
nums.reverse()
#reverse first k elements
reverse_elements(nums,0,k-1)
reverse_elements(nums,k,len(nums)-1)
#reverse remaining elements
Rotate Array — తరచూ అడిగే ప్రశ్నలు
Rotate Array వెనుక ఉన్న intuition ఏమిటి?
Rotating right by k moves the last k elements to the front. Reverse the whole array (they're now at the front, but backwards), then reverse the first k and the rest separately to fix both halves.
Rotate Array (LeetCode 189) ను ఎలా పరిష్కరించాలి?
1. Reduce k modulo n. 2. Reverse the entire array. 3. Reverse nums[0..k−1]. 4. Reverse nums[k..n−1].
Rotate Array యొక్క time, space complexity ఎంత?
Time: O(n). Space: O(1). (Accepted approach: Triple reverse.)
Rotate Array లో సాధారణ పొరపాట్లు ఏమిటి?
k can exceed n — take k % n first.