Tensorum
YouTubeகற்கத் தொடங்குங்கள்
LeetCode 189 · Two Pointers

Rotate Array

LeetCode 189 · நடுத்தரம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ

Reverse all, reverse first k, reverse the rest.

நடுத்தரம்ArrayMathTwo Pointers
LeetCode இல் திற ↗

நான் 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.