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
Rotate Array - Extra Array Approach INPUT Original Array (nums): 1 2 3 4 5 6 7 0 1 2 3 4 5 6 k = 3 (rotate right) Last 3 elements move to front 5 6 7 Elements to rotate Input Values: nums = [1,2,3,4,5,6,7] k = 3, n = 7 ALGORITHM STEPS 1 Create Extra Array temp[] of same size n=7 2 Calculate New Position newIndex = (i + k) % n 3 Copy to New Position temp[newIndex] = nums[i] 4 Copy Back to nums nums[i] = temp[i] Index Mapping (i+k)%n: i=0: (0+3)%7 = 3 i=1: (1+3)%7 = 4 i=2: (2+3)%7 = 5 i=3: (3+3)%7 = 6 i=4: (4+3)%7 = 0 i=5: (5+3)%7 = 1 i=6: (6+3)%7 = 2 1-->pos3, 2-->pos4, ... 5-->pos0, 6-->pos1, 7-->pos2 FINAL RESULT Rotated Array: 5 6 7 1 2 3 4 0 1 2 3 4 5 6 Output: [5,6,7,1,2,3,4] OK - Rotated by 3! Complexity Analysis: Time: O(n) - One pass to copy to temp - One pass to copy back Space: O(n) - Extra array of size n Key Insight: The Extra Array approach uses formula: newIndex = (oldIndex + k) % n to calculate each element's new position. The modulo operation handles wrap-around when (index + k) exceeds array length. This is intuitive but uses O(n) extra space. For O(1) space, use the reversal approach instead. TutorialsPoint - Rotate Array | Extra Array Approach
Asked in
Microsoft 45 Amazon 38 Google 32 Apple 28
78.0K Views
Very High Frequency
~15 min Avg. Time
2.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen