LeetCode #189 Medium

Rotate Array

Rotate Array is LeetCode 189 (Medium). You are given an integer array nums and a number k. Rotate the array to the right by k steps, in place: each value moves k places to the right, and values that fall off the end wrap around to the front.

  • In place: change nums itself; the function returns nothing.
  • k can be larger than n: k goes up to 10⁵, while the array may be much shorter.

The follow-up asks for O(1) extra space, which rules out copying into a second array.

Constraints
  • 1 <= nums.length <= 10⁵
  • -2³¹ <= nums[i] <= 2³¹ - 1
  • 0 <= k <= 10⁵
arraytwo-pointersin-place
Open on LeetCode ↗
02

Intuition

Rotating right by k cuts the array into two blocks, the first n − k values and the last k, and swaps the blocks while each block keeps its own order.

Reversing the whole array swaps the blocks, but it also turns each block backwards. Reversing each block once more turns it forwards again. So three reversals produce the rotation, and a reversal needs only two pointers and one swap at a time, so no extra array is used.

How to spot this pattern

When a problem asks to move a block of an array to the other end in place, think of reversals: reversing the whole array swaps two blocks, and reversing each block restores its order. The same trick reverses the words of a string in place.

03

Approach

Try it first

Before reading on, reverse [1, 2, 3, 4, 5, 6, 7] by hand, then reverse its first 3 values and its last 4. Compare the result with the array rotated right by 3.

1

Reduce k first

Rotating by n puts every value back where it started, so only the remainder counts: set k %= n. If k is now 0, there is nothing to do.

2

Reverse three times

Do the three reversals in this order:

  • Whole array: the last k values move to the front and the rest to the back, both backwards.
  • First k: turns the front block forwards again.
  • Last n − k: turns the back block forwards again.
3

Reverse with two pointers

To reverse nums[lo..hi], swap nums[lo] and nums[hi], then move lo right and hi left, until they meet. Each swap puts two values in place, so a range of length m takes m / 2 swaps and no extra memory.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def rotate(self, nums: List[int], k: int) -> None:
▶3 n = len(nums)
▶4 k %= n
▶5 if k == 0:
▶6 return
▶7 
▶8 def reverse(lo, hi):
▶9 while lo < hi:
▶10 nums[lo], nums[hi] = nums[hi], nums[lo]
▶11 lo += 1
▶12 hi -= 1
▶13 
▶14 reverse(0, n - 1)
▶15 reverse(0, k - 1)
▶16 reverse(k, n - 1)
nums10213243546576k = 3: the last 3 values move to the front
n7
k3k % n = 3
Start. Rotating right by 3 means the last 3 values, 5, 6, 7, end up at the front, in the same order. Three reversals do that in place.
nums70213243546516whole arrayswap 1 and 7
swapindex 0 ↔ 6
nums[7, 2, 3, 4, 5, 6, 1]
Reverse the whole array. Swap the two ends, then move both pointers inward. Afterwards the last 3 values will sit at the front, but backwards.
nums70613243542516whole arrayswap 2 and 6
swapindex 1 ↔ 5
nums[7, 6, 3, 4, 5, 2, 1]
Keep swapping the outer pair of the part not yet reversed.
nums70615243342516whole arrayswap 3 and 5
swapindex 2 ↔ 4
nums[7, 6, 5, 4, 3, 2, 1]
Keep swapping the outer pair of the part not yet reversed. This was the last pair: the front now holds 7, 6, 5, the right values in reverse order.
nums50617243342516first k = 3swap 7 and 5
swapindex 0 ↔ 2
nums[5, 6, 7, 4, 3, 2, 1]
Reverse the first 3. These are the values that belong at the front; the first reversal left them backwards, so reversing them again puts them in their original order.
nums50617213342546last n − k = 4swap 4 and 1
swapindex 3 ↔ 6
nums[5, 6, 7, 1, 3, 2, 4]
Reverse the last 4. The values that belong at the back are also backwards after the first reversal; one more reversal fixes their order.
nums50617213243546last n − k = 4swap 3 and 2
swapindex 4 ↔ 5
nums[5, 6, 7, 1, 2, 3, 4]
Next pair of the last 4.
nums50617213243546rotated right by 3
nums[5, 6, 7, 1, 2, 3, 4]
Done. [5, 6, 7, 1, 2, 3, 4] is the original array rotated right by 3. Every value was swapped at most twice, and no second array was used: O(n) time, O(1) extra space.
05

Common pitfalls

Forgetting k % n

✗ Wrong
reverse(0, n - 1)
reverse(0, k - 1)
✓ Right
k %= n
reverse(0, n - 1)
reverse(0, k - 1)

With nums = [1, 2] and k = 3, reverse(0, 2) reaches index 2, which does not exist: Python raises IndexError, and C++ reads and writes outside the array.

Splitting at n − k after the full reversal

✗ Wrong
reverse(0, n - k - 1)
reverse(n - k, n - 1)
✓ Right
reverse(0, k - 1)
reverse(k, n - 1)

After the whole array is reversed, the k values that belong at the front occupy the first k places. Splitting at n − k reverses the wrong blocks, and the array is rotated by the wrong amount.

06

Complexity

Time
O(n)
Space
O(1)
The three reversals make about n swaps in total; each value is swapped at most twice. Only two pointers and one temporary value are used.
07

Rotate Array FAQ

How do you write it in Python with slicing?

nums[:] = nums[-k:] + nums[:-k] after k %= len(nums). It is correct and short, but it builds a new list of n values, so it uses O(n) extra space instead of O(1). Write nums[:] =, not nums =: LeetCode checks the original list, and plain assignment only rebinds the local name.

How do you rotate an array to the left instead?

Swap the order of the reversals: reverse the first k, reverse the last n − k, then reverse the whole array. The GeeksforGeeks version of this problem rotates left (counter-clockwise), so check the direction before using this code.

Is there another O(1) space way?

Yes, cyclic replacement: move the value at index 0 to index k, the value found there to 2k, and so on, wrapping with % n, until the cycle returns to its start; then begin a new cycle at index 1. There are gcd(n, k) cycles. It is also O(n) time, but keeping count of cycles is easy to get wrong, so the three reversals are the usual answer.