Rotate a List to the Right

Medium ⏱ 12 min 60% acceptance ★★★★★ 4.9
Write rotate_right(items, k) that rotates items to the right by k positions and returns the new list. Elements that fall off the end reappear at the front. Handle k larger than len(items). Assume items is non-empty.

Examples

Example 1
Input
items = [1, 2, 3, 4, 5], k = 2
Output
[4, 5, 1, 2, 3]
Explanation

The last two elements move to the front.

Constraints

  • 1 <= len(items) <= 10^5
  • 0 <= k <= 10^9

Topics

ListsSlicing

Companies

AppleCisco

Hints

Hint 1

k %= len(items) first.

Hint 2

items[-k:] + items[:-k] works, but watch out for k == 0 (special-case it).

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.