Example 1
- Input
- nums = [1, 2, 3, 4, 5, 6, 7], k = 3
- Output
- [5, 6, 7, 1, 2, 3, 4]
One step right gives [7, 1, 2, 3, 4, 5, 6], two steps gives [6, 7, 1, 2, 3, 4, 5], three steps gives [5, 6, 7, 1, 2, 3, 4].
Move each array element k positions to the right, wrapping past the end to the front. Modify the original array; three reversals do this in linear time with constant extra space.
Given an integer array nums and a non-negative integer k, rotate the array to the right by k steps. A one-step right rotation moves the last element to the front. Update nums itself; the methods shown return no separate result.
A full rotation of n steps restores an array of length n, so only k % n changes the result. Follow-up: can you perform the rotation in place using extra space?
1 <= nums.length <= 10^5-2^31 <= nums[i] <= 2^31 - 10 <= k <= 10^5One step right gives [7, 1, 2, 3, 4, 5, 6], two steps gives [6, 7, 1, 2, 3, 4, 5], three steps gives [5, 6, 7, 1, 2, 3, 4].
One step right gives [99, -1, -100, 3], two steps gives [3, 99, -1, -100].
Three steps form a full cycle, so five steps have the same effect as two. Move the final block [2, 3] before [1].
Zero steps leave the array unchanged. With only one position, any allowed k would also leave it unchanged.
Cut the array into two blocks: A is the first n - k values and B is the last k, after reducing k by the length. Right rotation changes A followed by B into B followed by A, preserving the order inside each block. In [1, 2, 3, 4, 5, 6, 7] with k = 3, A is [1, 2, 3, 4] and B is [5, 6, 7]; the result is [5, 6, 7, 1, 2, 3, 4]. Modulo arithmetic chooses the destination directly, while reversal moves these blocks without a helper array.
Reveal Extra Array: intuition, complexity, and code
10^5 elements.k % n.k block and the back block separately to fix both orders.k = 0 or a multiple of n leaves every value in place. [1, 2, 3] with k = 6 is unchanged.[1, 2, 3] with k = 5 becomes [2, 3, 1].[2, 2, 1] with k = 1 becomes [1, 2, 2].(i + k) % n.k - 1, and the second starts at k. Normalize k before using it as a boundary.nums = helper only changes a local reference in these languages; copy entries into the caller's original array.Array rotation is a block reorder. Modulo removes complete cycles, and whole-array plus block reversals exchange two adjacent blocks while preserving order with constant auxiliary space.