DSA Factory
Free Arrays lessonsArrays · Stage 4 · Rotation · Step 2

Rotate by k, with a copy

Send each value straight to where it ends up. About 9 minutes.

Jump straight to where each value lands

Rotating right by one, k times over, repeats a lot of shuffling. Instead, work out where each value ends up and put it there directly: every value moves k boxes to the right.

If that goes past the end, it wraps round to the front, like the hands of a clock going past 12. A value 2 boxes from the end, moving 3 places, lands in box 1.

Each value moves k boxes right: and wraps round past the end.
Rotate [10, 20, 30, 40, 50] right by 2
10
0
20
1
30
2
40
3
50
4
ilands

10 is in box 0. Two places to the right is box 2.

Move 1 of 4

The remainder does the wrapping

The remainder operator is a clock for box numbers. Divide by the length and keep the remainder, and any number wraps back into the range of real boxes. In a row of 5, box "6" becomes box 1.

Rotating by the full length changes nothing, just as a clock that moves 12 hours shows the same time. So shrink k to its remainder first. And check for an empty array before dividing by its length.

Rotating by the length: changes nothing, so shrink k first.
Empty array: check it before dividing by the length.
In code
n = len(nums)
if n == 0:
    return nums
k = k % n
result = [0] * n
for i in range(n):
    result[(i + k) % n] = nums[i]
return result
Quick check

An array of 4 values is rotated right by 6. Where does the value in box 3 end up?

  1. ABox 1
  2. BBox 9
  3. CBox 3
Show the answer

Box 1. Rotating by 6 is the same as rotating by 2 (6 minus a full turn of 4). Box 3 moves 2 along and wraps round to box 1.

Your problem

Rotate by k

Rotate the list right by k places and return the result. You may build a new list. k can be larger than the length.

Example
nums = [10, 20, 30, 40, 50], k = 2 → [40, 50, 10, 20, 30]

0 ≤ n ≤ 1,000 · 0 ≤ k ≤ 1,000,000

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve