Tensorum
LeetCode 189 · Two Pointers

Rotate Array

LeetCode 189 · Medium · solution, intuition & step-by-step walkthrough

Reverse all, reverse first k, reverse the rest.

MediumArrayMathTwo Pointers
3 msruntime · beats 100%
27.1 MBmemory · beats 100%
1approach
8accepted runs · last 26 May 2026

This is how I solved Rotate Array (LeetCode 189), a medium problem from the Two Pointers pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a 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].

How I solved it

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

Loading the step-through…

Rotate Array — FAQ

What is the intuition behind Rotate Array?

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.

How do you solve 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].

What is the time and space complexity of Rotate Array?

Time: O(n). Space: O(1). (Accepted approach: Triple reverse.)

What are common mistakes in Rotate Array?

k can exceed n — take k % n first.