You are given an integer array nums and a whole number k. Shift every value k places to the right, in place. A value pushed off the right end comes back in at the left end.
Change nums itself; there is nothing to return.
Example 1
Input: nums = [3, 8, 1, 9, 4], k = 2 Output: [9, 4, 3, 8, 1] Why: the last two values, 9 and 4, wrap to the front
2 more examples and the constraints
Example 2
Input: nums = [10, 20, 30], k = 4 Output: [30, 10, 20] Why: 4 shifts on 3 values is the same as 1 shift
Example 3
Input: nums = [7, -2, 5], k = 0 Output: [7, -2, 5] Why: zero shifts leave the array as it is
Constraints
- 1 ≤ nums.length ≤ 100,000
- −2³¹ ≤ nums[i] ≤ 2³¹ − 1
- 0 ≤ k ≤ 100,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Shift one step at a timeO(n · k)
- Copy to a new arrayO(n)
- Reverse three timesO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for n = 100,000, k = 50,000 | Verdict |
|---|---|---|---|
| Shift one step at a time | O(n · k) | Times out on large k | |
| Copy to a new array | O(n) | Passes; uses O(n) memory | |
| Reverse three times | O(n) | Best; in place |
n = length of nums, k = steps to rotate.
Edge cases to test
- k larger than n. Rotating by n is a no-op, so use
k % n. k = 4 on 3 values is one shift. - k = 0 or k = n. The array must come back unchanged.
- One value. Any k leaves
[42]as[42];k % 1is 0. - Extreme values. −2³¹ and 2³¹ − 1 only move, never add, so nothing overflows.
Common mistakes
- Skipping
k %= n, so the index math or the reversal runs past the end. - Building a new array and assigning it to the local name, so the caller’s array never changes.
- Reversing the first n − k values instead of the first k after the full reversal.
How to talk through it
- 1Clarify. Must it be in place? Can k be larger than the array? Rotate right, not left?
- 2Give the simple ways. Shift k times is O(n · k); a second array with index
(i + k) % nis O(n) time and space. - 3Show the reversal idea. Reversing all swaps the two blocks; reversing each block fixes their inner order.
- 4Code it with one helper. A two-pointer
reverse(i, j)called three times. - 5Test out loud. Run k = 0, k = n, k > n and a single value before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?