Given a list of integers nums and an integer k, rotate the list k positions to the right and return the rotated list. One step of right rotation moves the last element to the front and shifts every other element one place toward the end.
Function Signature
def rotate_right(nums: list[int], k: int) -> list[int]:
Rules
-
Values that move past the last index wrap around to the front and keep their relative order.
-
Return the rotated values as a new list and leave
nums
unchanged.
-
With
k = 0
the values come back in their original order.
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]
The last two values, 4 and 5, wrap around to the front in their original order, and 1, 2, 3 follow them.
Input: nums = [10, 20, 30, 40], k = 3
Output: [20, 30, 40, 10]
The last three values move to the front and 10 ends up last. Rotating a list of four values right by 3 gives the same result as rotating it left by 1.
Input: nums = [7, -3, 5], k = 0
Output: [7, -3, 5]
A rotation by zero positions changes nothing.