Rotate an array to the right
Reported in interviews at (where)
- Spire Technologies
- GlobalLogic
Move every element of nums k places to the right. An element pushed off the end comes back in at the start.
Return the rotated array. k may be larger than the length of the array. Try it with O(1) extra memory.
- Input
nums = [10,20,30,40,50]
k = 2- Output
[40,50,10,20,30]
The last two elements come round to the front.
- Input
nums = [1,2,3]
k = 4- Output
[3,1,2]
Rotating by 3 changes nothing, so rotating by 4 is the same as rotating by 1.
Limits
1 <= nums.length <= 100000-1000000000 <= nums[i] <= 10000000000 <= k <= 1000000000
Hints
Hint 1
Only k modulo the length matters.
Hint 2
Reverse the whole array, then reverse the first k elements and the rest separately.
Where this was reported
- Spire Technologies, SDE interview, 2024 (GeeksforGeeks)
- GlobalLogic, On-campus interview, 2017 (GeeksforGeeks)
Our own problem on the task these candidates describe; the wording, examples and tests are InternDoor’s.
Run your code to check it on the examples. Submit runs every hidden test.
