Menu
CoddyTech

Rotate Array

You get an array of integers nums and a number k. Rotate the array to the right by k steps: in one step every value moves one place to the right, and the last value wraps around to the front. Return the rotated array.

k can be far larger than the length of the array.

Function

rotate(nums: integer-array, k: integer) → integer-array
numsinteger-array
the array of integers to rotate
kinteger
how many steps to rotate to the right
Returnsinteger-array
nums rotated to the right by k steps

Constraints

  • 1 ≤ nums.length ≤ 5000
  • -104 ≤ nums[i] ≤ 104
  • 0 ≤ k ≤ 109

Examples

Input
nums = [4, 9, 1, 6, 3]k = 2
Output
[6, 3, 4, 9, 1]
Explanation
Two steps to the right carry the last two values, 6 and 3, around to the front. The other three values move two places right and keep their order: [6, 3, 4, 9, 1].
challenge icon

Follow-up

Can you rotate in place by moving each value straight to (i + k) mod n and carrying the value it displaces onward? How many cycles does that make?

Reset code
def rotate(nums, k):
    # Write code here

Test #1

Test #2

Test #3

Arguments

nums = [4, 9, 1, 6, 3]
k = 2

Expected Output

[6, 3, 4, 9, 1]