easy +8 pts

Rotate List Right by k

Rotate a list to the right by a given number of steps.

Write a function `rotate_right(nums, k)` that takes a list of integers `nums` and a non-negative integer `k` and returns a new list rotated to the right by `k` positions. A right rotation by 1 moves the last element to the front and shifts all other elements one position to the right. If `k` is larger than the length of the list, only `k % len(nums)` rotations matter (if the list is empty, return an empty list). The original list must not be modified.

Constraints

- 0 <= len(nums) <= 1000 - 0 <= k <= 10^9 - The function should work in O(n) time and O(n) extra space (for the output).

Example

>>> rotate_right([1, 2, 3, 4, 5], 2)
[4, 5, 1, 2, 3]
>>> rotate_right([1, 2, 3], 5)
[2, 3, 1]
>>> rotate_right([], 10)
[]
8 points ~10 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

If the list is empty, return it immediately.
Use modulo to handle k larger than the list length.
Think of slicing: elements from len(nums)-k to end come first, then the rest.
Return a new list; do not mutate the input.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.