Skip to content
Onsite

Rotate Array

MediumP2Coding

Rotate the array nums to the right by k steps, in place. Rotating by one step moves the last element to the front and shifts every other element one place to the right.

k may be larger than the array length. Use O(1) extra space.

Example 1

Input
nums = [1,2,3,4,5,6,7], k = 3
Output
[5,6,7,1,2,3,4]
Why
Rotating 3 steps gives [5,6,7,1,2,3,4].

Example 2

Input
nums = [-1,-100,3,99], k = 2
Output
[3,99,-1,-100]
Why
Two steps: [-1,-100,3,99] -> [99,-1,-100,3] -> [3,99,-1,-100].

Example 3

Input
nums = [1], k = 5
Output
[1]

Constraints

  • 1 <= nums.length <= 10^5
  • -2^31 <= nums[i] <= 2^31 - 1
  • 0 <= k <= 10^9

Hints

Run checks the 3 visible tests, Submit all 10.