Write a Python function that takes a list of integers nums and rotates it k positions to the right, returning the rotated list. Rotating right by one position moves the last element to index 0 and pushes every other element one place toward the end.
Function Signature
def rotate_right(nums: list[int], k: int) -> list[int]:
Rules
-
Elements that move past the end reappear at the start, in the same circular order.
-
Return a new list with the rotated values;
nums
itself is not modified.
-
With
k = 0
the result has the same values in the same order as
nums
.
Constraints
-
1 <= len(nums) <= 10^4
-
-10^4 <= nums[i] <= 10^4
-
0 <= k < len(nums)
Examples
Input: nums = [1, 2, 3, 4, 5], k = 2
Output: [4, 5, 1, 2, 3]
Two right steps carry 5 and then 4 around to the front, so the list starts with 4, 5 and continues with 1, 2, 3.
Input: nums = [10, 20, 30, 40], k = 3
Output: [20, 30, 40, 10]
The last three values wrap to the front and 10 is pushed to the last index.
Input: nums = [-4, 0, 9], k = 1
Output: [9, -4, 0]
A single right step moves 9 from the end to index 0.