Back

Rotate Array

medium

Given an integer array nums, rotate the array to the right by k steps, where k is non-negative.

Try to come up with as many solutions as you can — there are at least three different ways to solve this problem. Can you do it in-place with O(1) extra space?

Test Cases

Copy an input into the main harness and Run to verify
Input
nums = [1,2,3,4,5,6,7], k = 3
Expected Output
[5,6,7,1,2,3,4]

Explanation: Rotating right three times moves the last three elements to the front.

Input
nums = [-1,-100,3,99], k = 2
Expected Output
[3,99,-1,-100]

Constraints

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

Hints

Hint 1 — click to reveal

k can exceed the array length — reduce it with a modulo first.

Hint 2 — click to reveal

Reversing the whole array puts the right elements in front, just backwards. What would fix that?

Java Compiler

Powered by OneCompiler. Starter code loads automatically — edit and hit Run.