DSA AnimatorDSA animations
Rotate Array LC #189 Medium Array
Problem

Given an integer array nums, rotate the array to the right by k steps, where k is non-negative. Must be done in-place with O(1) extra space.

Example 1
Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
Explanation: rotate 1 step → [7,1,2,3,4,5,6], 2 steps → [6,7,1,2,3,4,5], 3 steps → [5,6,7,1,2,3,4].
Constraints: 1 ≤ nums.length ≤ 10⁵  |  −2³¹ ≤ nums[i] ≤ 2³¹−1  |  0 ≤ k ≤ 10⁵
Try Examples
Custom:
Approach
Triple Reverse — In-Place O(1) Space
Reverse the full array, then reverse the first k elements, then reverse the remaining n−k elements. Three passes, no extra array needed. O(n) time, O(1) space!
Array
—
Variables
Phase
—
L
—
R
—
k
—
Step Logic
Press ▶ Play or Next Step to begin.
🎉
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
Normalize k = k % n
2
Reverse entire array [0..n-1]
3
Reverse first k elements [0..k-1]
4
Reverse remaining [k..n-1]
Time
O(n)
Space
O(1)
Why It Works

Rotating right by k is equivalent to bringing the last k elements to the front. Reversing all elements flips the order. Reversing the first k elements fixes the "last k" portion into sorted order. Reversing the remaining n−k elements fixes the "first n−k" portion. Three in-place reversals = one rotation.

How to solve Rotate Array

LeetCode 189 · Medium · Arrays · Pattern: Reversal

Why the obvious approach is slow

Rotating one step at a time, k times, is O(n) times k. Copying into a new array works in O(n) time, but uses O(n) space.

The key idea

Three reversals do the whole rotation in place. Reverse the whole array, then reverse the first k numbers, then reverse the rest. If k is larger than the length, use k mod n first.

Remember

Rotate right by k means reverse all, reverse the first k, reverse the rest. Always take k mod n first.

Run the animation above on your own input, or watch the 1:24 video explanation of Rotate Array with a dry run and Java code.

More Arrays problems