Rotate Array (LeetCode 189): Solution and Explanation

Medium
Array
Math
Two Pointers

Shift every element of an array k positions to the right, with elements that fall off the end wrapping around to the front. The rotation has to happen inside the given array using only constant extra memory.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The most literal approach rotates by one position, k times: save the last element, shift everything right by one, and put the saved element at index 0. That is O(n × k), which is far too slow when both are large. Copying into a new array, where each element moves to (i + k) % n, is O(n) time but needs O(n) extra memory, which the in-place requirement rules out.

Start by noticing that rotating by n leaves the array unchanged, so only k % n matters. Then look at what a right rotation does to the array's structure. Split the array into two blocks: the first n - k elements, call them A, and the last k, call them B. The array is A followed by B, and the rotated array is B followed by A. The goal is to swap the order of two adjacent blocks without a buffer.

Reversal does that. Reversing the whole array turns A B into reverse(B) followed by reverse(A). Now B is at the front where it belongs, just backward, and A is at the back, also backward. Reversing each block on its own puts both back into their original internal order, giving B A.

Each reversal is a simple two pointer swap from the outside in, so the whole rotation touches every element about twice and needs no extra array.

Approach: Three reversals

  1. Reduce the rotation with k = k % len(nums), since rotating by the length is a no-op.
  2. Define reverse(l, r) that swaps nums[l] and nums[r] and moves both pointers inward until they meet.
  3. Reverse the entire array with reverse(0, len(nums) - 1).
  4. Reverse the first k elements with reverse(0, k - 1), restoring the order of the block that moved to the front.
  5. Reverse the remaining elements with reverse(k, len(nums) - 1), restoring the order of the back block.

Step-by-step example

nums = [1,2,3,4,5,6,7], k = 3
  1. k % 7 is still 3. The block that should move to the front is [5,6,7].
  2. Reversing the whole array gives [7,6,5,4,3,2,1].
  3. Reversing the first three elements turns [7,6,5] into [5,6,7], giving [5,6,7,4,3,2,1].
  4. Reversing indices 3 through 6 turns [4,3,2,1] into [1,2,3,4], giving [5,6,7,1,2,3,4].
  5. That is the array rotated three steps to the right.

Code: Python, Java, C++

1class Solution:
2    def rotate(self, nums: List[int], k: int) -> None:
3        k = k % len(nums)  # Handle k > len(nums)
4
5        def reverse(l, r):
6            while l < r:
7                nums[l], nums[r] = nums[r], nums[l]
8                l, r = l + 1, r - 1
9
10        reverse(0, len(nums) - 1)  # Reverse all
11        reverse(0, k - 1)           # Reverse first k
12        reverse(k, len(nums) - 1)   # Reverse rest

Time and space complexity

Time

O(n)

The three reversals together swap each element at most twice, so the total work is proportional to the array length.

Space

O(1)

Only a couple of index variables are used. All swaps happen inside nums.

Other approaches

Extra array (time O(n), space O(n))

Create a copy and write each element to index (i + k) % n, then copy back into nums. It is the easiest to get right and is fine when memory is not constrained.

Cyclic replacements (time O(n), space O(1))

Pick up an element, drop it at its target index, pick up the element that was there, and keep going until you return to the start; repeat from the next start index until n elements have moved. It moves each element exactly once in place but is trickier to reason about, because the number of cycles equals gcd(n, k).

Common mistakes

  • Skipping k % n. When k is larger than the array, reverse(0, k - 1) reads past the end.
  • Rotating left instead of right by reversing the wrong blocks, for example reversing the first n - k elements in the second step.
  • Assigning nums = nums[-k:] + nums[:-k] in Python. That rebinds the local name to a new list and leaves the caller's array untouched; you would need slice assignment with nums[:] = nums[-k:] + nums[:-k], which uses O(n) extra space.
  • Using k = k % n on an empty array, which divides by zero. The constraints guarantee at least one element, but defensive code should check.

Frequently asked questions

Why does reversing three times rotate the array?

Think of the array as block A followed by block B, where B is the last k elements. Reversing everything gives reverse(B) then reverse(A), and reversing each block again restores their internal order, leaving B then A, which is the rotation.

How do you rotate an array in place with O(1) space?

Use the three-reversal trick or cyclic replacements. Both move elements within the array using only a few variables, and both run in O(n) time.

What if k is larger than the array length?

Rotating by the array length returns the array to its original order, so only k % n steps matter. Reducing k first also keeps the reversal indices in range.