Rotate Array - Problem
Given an integer array nums, rotate the array to the right by k steps, where k is non-negative.
Example: If nums = [1,2,3,4,5,6,7] and k = 3, after rotation the array becomes [5,6,7,1,2,3,4].
Note: Try to solve this problem in-place with O(1) extra memory.
Input & Output
Example 1 — Basic Rotation
$
Input:
nums = [1,2,3,4,5,6,7], k = 3
›
Output:
[5,6,7,1,2,3,4]
💡 Note:
Rotate right by 3: the last 3 elements [5,6,7] move to the front, and [1,2,3,4] shift to the back
Example 2 — Small Array
$
Input:
nums = [-1,-100,3,99], k = 2
›
Output:
[3,99,-1,-100]
💡 Note:
Rotate right by 2: [3,99] moves to front, [-1,-100] moves to back
Example 3 — No Change
$
Input:
nums = [1,2], k = 2
›
Output:
[1,2]
💡 Note:
k equals array length, so after full rotation the array remains unchanged
Constraints
- 1 ≤ nums.length ≤ 105
- -231 ≤ nums[i] ≤ 231 - 1
- 0 ≤ k ≤ 105
Visualization
Tap to expand
Understanding the Visualization
1
Input
Original array [1,2,3,4,5,6,7] and rotation steps k=3
2
Process
Elements move k positions to the right, with wraparound
3
Output
Rotated array [5,6,7,1,2,3,4]
Key Takeaway
🎯 Key Insight: Three array reversals can achieve any rotation in O(1) space
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code