Rotate Array
Rotate Array
Rotate an integer slice to the right by k steps in-place. That is, each element moves to (i + k) % n.
The straightforward approach of shifting one step at a time is O(n*k) and too slow for large k. The goal is O(n) time and O(1) extra space.
Function signature
func RotateArray(nums []int, k int)
Inputs / outputs
nums: the slice to rotate in-place.k: number of steps to rotate right.- Return: nothing;
numsis modified in-place.
Example
nums = [1,2,3,4,5,6,7], k = 3
After rotation: [5,6,7,1,2,3,4]
Constraints
0 <= len(nums) <= 100_0000 <= k <= 1_000_000_000
Core idea (near-solution)
Use the reverse trick:
- Reverse the entire slice.
- Reverse the first
kelements. - Reverse the remaining
n-kelements.
This works because reversing moves the last k elements to the front, and then the two additional reversals restore the order within each block.
Invariant: after each reverse, the relative order inside the reversed segment is fixed for the final result.
Algorithm (step-by-step)
- Let
n = len(nums). Ifn == 0, return. - Reduce
kwithk %= n. - Reverse
nums[0:n-1]. - Reverse
nums[0:k-1]. - Reverse
nums[k:n-1].
Correctness sketch
- Invariant: after each reverse, the relative order inside the reversed segment is fixed for the final result.
- Reversing segments rearranges indices deterministically.
- The sequence of reversals maps each element to its rotated position.
- Thus the final array is exactly the desired rotation.
Trace (hand walkthrough)
Trace Walkthrough
Example input:
nums = [1,2,3,4,5,6,7], k = 3
After rotation: [5,6,7,1,2,3,4]
Walk:
- k=3, reverse all: [7,6,5,4,3,2,1]
- reverse first k=3: [5,6,7,4,3,2,1]
- reverse rest: [5,6,7,1,2,3,4]
Pitfalls to avoid
- Forgetting
k %= n(causes out-of-bounds or redundant work). - Using extra slices (violates in-place requirement).
- Mixing up left and right rotation.
Complexity
- Time:
O(n) - Extra space:
O(1)
Implementation notes (Go)
- Implement a helper
reverse(nums []int, l, r int)that swaps in-place. - Check for
n == 0beforek %= nto avoid division by zero.
Run tests to see results
No issues detected