← Back to DSA Animator
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.