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.