← switch

189. Rotate Array

medium

Array · Math · Two Pointers

read the problem on leetcode →

first solved 13 Aug 2024 · 2 accepted submissions

python
class Solution:
    def rotate(self, nums: list[int], k: int) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        def rev(left, right):
            while left< right:
                nums[left], nums[right]= nums[right], nums[left]
                left+=1
                right-=1
        
        n=len(nums)
        k=k%n
        rev(0,n-1)
        rev(0,k-1)
        rev(k,n-1)


        
python
class Solution:
    def rotate(self, nums: List[int], k: int) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        k=k%len(nums)
        if k!=0:
            nums[:k],nums[k:]=nums[-k:],nums[:-k]