InternDoor

Rotate an array to the right

Easyarrays · reversal

Reported in interviews at (where)

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.

Example 1
Input
nums = [10,20,30,40,50]
k = 2
Output
[40,50,10,20,30]

The last two elements come round to the front.

Example 2
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] <= 1000000000
  • 0 <= 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

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.

Ready for the real one?

Engineering internships and entry-level jobs in India, newest first.