7. Rotate Array
Medium · Array
Given an array and a rotation count, rotate the array to the right by k steps. Rotation means moving elements from the end of the array to the beginning.
For example, rotating [1, 2, 3, 4, 5] right by 2 steps gives [4, 5, 1, 2, 3].
You must solve this in-place with O(1) extra space (not counting the output array itself).
Examples
Example 1 Input: nums = [1, 2, 3, 4, 5], k = 2 Output: [4, 5, 1, 2, 3] Explanation: Rotate right by 2: take the last 2 elements [4, 5] and move them to the front.
Example 2 Input: nums = [1, 2, 3, 4, 5], k = 7 Output: [4, 5, 1, 2, 3] Explanation: k = 7 is equivalent to k = 2 (since 7 % 5 = 2). Rotate right by 2 steps.
Constraints
- Standard input/output constraints apply