Editor

Rotate a List

#55 · Lists · Intermediate · 55 XP · about 8 min

Write rotate(nums, k) that returns a new list with the items of nums rotated k steps to the right: each step moves the last item to the front. Leave nums itself unchanged.

k can be larger than the length of the list, and a negative k rotates to the left instead.

Examples

rotate([1, 2, 3, 4, 5], 2)  # returns [4, 5, 1, 2, 3]
rotate([1, 2, 3], 4)        # returns [3, 1, 2]
rotate([1, 2, 3, 4], -1)    # returns [2, 3, 4, 1]

Rotating a list of 3 items by 4 steps ends in the same place as rotating it by 1 step.

Constraints

  • 0 <= len(nums) <= 100,000
  • k is between -10**9 and 10**9

Ready?

Accept the challenge to start writing. A small timer counts the time this page is in view.

Output appears here.