Skip to content
Problem 189 · LeetCode 189(opens in a new tab)

Rotate Array

MediumArrays

You are given an integer array nums and a whole number k. Shift every value k places to the right, in place. A value pushed off the right end comes back in at the left end.

Change nums itself; there is nothing to return.

Example 1

Input:  nums = [3, 8, 1, 9, 4], k = 2
Output: [9, 4, 3, 8, 1]
Why:    the last two values, 9 and 4, wrap to the front
2 more examples and the constraints

Example 2

Input:  nums = [10, 20, 30], k = 4
Output: [30, 10, 20]
Why:    4 shifts on 3 values is the same as 1 shift

Example 3

Input:  nums = [7, -2, 5], k = 0
Output: [7, -2, 5]
Why:    zero shifts leave the array as it is

Constraints

  • 1 ≤ nums.length ≤ 100,000
  • −2³¹ ≤ nums[i] ≤ 2³¹ − 1
  • 0 ≤ k ≤ 100,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Shift one step at a timeO(n · k)
  2. Copy to a new arrayO(n)
  3. Reverse three timesO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for n = 100,000, k = 50,000Verdict
Shift one step at a timeO(n · k)
Times out on large k
Copy to a new arrayO(n)
Passes; uses O(n) memory
Reverse three timesO(n)
Best; in place

n = length of nums, k = steps to rotate.

Edge cases to test

  • k larger than n. Rotating by n is a no-op, so use k % n. k = 4 on 3 values is one shift.
  • k = 0 or k = n. The array must come back unchanged.
  • One value. Any k leaves [42] as [42]; k % 1 is 0.
  • Extreme values. −2³¹ and 2³¹ − 1 only move, never add, so nothing overflows.

Common mistakes

  • Skipping k %= n, so the index math or the reversal runs past the end.
  • Building a new array and assigning it to the local name, so the caller’s array never changes.
  • Reversing the first n − k values instead of the first k after the full reversal.

How to talk through it

  1. 1Clarify. Must it be in place? Can k be larger than the array? Rotate right, not left?
  2. 2Give the simple ways. Shift k times is O(n · k); a second array with index (i + k) % n is O(n) time and space.
  3. 3Show the reversal idea. Reversing all swaps the two blocks; reversing each block fixes their inner order.
  4. 4Code it with one helper. A two-pointer reverse(i, j) called three times.
  5. 5Test out loud. Run k = 0, k = n, k > n and a single value before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?