Rotate Array Right
EasyArray · Microsoft
Given an integer array nums and a non-negative integer k, rotate the array to the right by k steps. One step moves the last element to the front and shifts every other element one position to the right.
Rotate in place: modify nums directly and return nothing. The grader checks the contents of nums after your function returns. k can be larger than the length of the array.
Follow-up: can you do it with O(1) extra space?
Example 1
- Input:
- nums = [10,20,30,40,50], k = 2
- Output:
- [40,50,10,20,30]
- Explanation
- After one step the array is [50,10,20,30,40]; after the second it is [40,50,10,20,30]. The last two values wrap around to the front.
Example 2
- Input:
- nums = [4,8,15], k = 7
- Output:
- [15,4,8]
- Explanation
- Rotating a length-3 array by 3 steps returns it to the start, so 7 steps act like 7 % 3 = 1 step.
Example 3
- Input:
- nums = [-6,2], k = 0
- Output:
- [-6,2]
- Explanation
- Zero steps leave the array unchanged.
Constraints
1 <= nums.length <= 10^5-2^31 <= nums[i] <= 2^31 - 10 <= k <= 10^5