Tensorum
YouTubeसीखना शुरू करें
LeetCode 189 · Two Pointers

Rotate Array

LeetCode 189 · मध्यम · समाधान, intuition और कदम-दर-कदम वॉकथ्रू

Reverse all, reverse first k, reverse the rest.

मध्यमArrayMathTwo Pointers

मैंने 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. 1

    Reduce k modulo n.

  2. 2

    Reverse the entire array.

  3. 3

    Reverse nums[0..k−1].

  4. 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.