Rotate Array - Problem
Array Rotation Challenge: You're given an integer array nums and need to rotate it to the right by exactly k steps. Think of it like a conveyor belt - elements that fall off the right end wrap around to the beginning!

For example, if you have [1,2,3,4,5] and rotate right by 2 steps, elements 4 and 5 move to the front, giving you [4,5,1,2,3].

Goal: Transform the array in-place (modify the original array) to achieve the rotation efficiently.

Input & Output

example_1.py โ€” Basic Rotation
$ Input: nums = [1,2,3,4,5,6,7], k = 3
โ€บ Output: [5,6,7,1,2,3,4]
๐Ÿ’ก Note: Rotating right by 3 steps: elements 5,6,7 from the end move to the front, and 1,2,3,4 shift right
example_2.py โ€” Small Array
$ Input: nums = [-1,-100,3,99], k = 2
โ€บ Output: [3,99,-1,-100]
๐Ÿ’ก Note: With k=2, the last 2 elements (3,99) move to the front, and the first 2 elements (-1,-100) move to the end
example_3.py โ€” k Larger Than Array
$ Input: nums = [1,2], k = 3
โ€บ Output: [2,1]
๐Ÿ’ก Note: k=3 is equivalent to k=3%2=1, so we rotate right by 1 step: [1,2] becomes [2,1]

Visualization

Tap to expand
Three Reversals AlgorithmOriginal: [1,2,3,4,5] k=212345Step 1: Reverse All โ†’ [5,4,3,2,1]54321Step 2: Reverse First k=2 โ†’ [4,5,3,2,1]45321Step 3: Reverse Last n-k=3 โ†’ [4,5,1,2,3]45123โœจ Magic!Three simple reversalsachieve perfect rotation
Understanding the Visualization
1
Flip Entire Deck
First, flip the entire deck upside down
2
Flip First k Cards
Then flip just the first k cards back
3
Flip Remaining Cards
Finally, flip the remaining cards back
Key Takeaway
๐ŸŽฏ Key Insight: Any array rotation can be achieved with exactly three reversals: reverse all, reverse first k, reverse last n-k. This transforms a complex problem into simple array manipulations!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Each element is moved exactly once, so we do n operations total

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only uses a few variables to track current position and temporary values

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค nums.length โ‰ค 105
  • -231 โ‰ค nums[i] โ‰ค 231 - 1
  • 0 โ‰ค k โ‰ค 231 - 1
  • Follow-up: Try to solve in-place with O(1) extra space
Asked in
Microsoft 45 Amazon 38 Google 32 Meta 28
42.9K Views
High Frequency
~15 min Avg. Time
1.3K 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