Rotate Array

MediumArrays · Reversal Trick🧩 Array ManipulationLeetCode #189 ↗Updated

Problem

Shift the elements of nums to the right by k positions, in-place. Elements pushed off the end wrap around to the front, so after the rotation the value at index i ends up at index (i + k) % n. Note k may be larger than the array length.
Inputnums = [1,2,3,4,5,6,7], k = 3Output[5,6,7,1,2,3,4]
Inputnums = [-1,-100,3,99], k = 2Output[3,99,-1,-100]
Inputnums = [1,2], k = 5Output[2,1] (5 % 2 = 1)

1 ≤ n ≤ 105  ·  -231 ≤ nums[i] ≤ 231-1  ·  0 ≤ k ≤ 105  ·  Follow-up: O(1) extra space.

Try it yourself

Java
class Solution {
    public void rotate(int[] nums, int k) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
A right rotation by k moves the last k items to the front with both blocks keeping their order. Reverse the whole array, then reverse each block back: the blocks swap places and each is restored.
PatternArray Manipulation

Instinct "In place", "O(1) extra space" or "one pass" over an array? Think write pointer, reversal, prefix/suffix passes or using indices as storage.

Memory hack Read fast, write slow, reverse to rotate, and let the index be the hash.

Open the Array Manipulation guide →

Approaches

Brute ForceRotate One Step, k Times

Time O(n·k)Space O(1)

A single right rotation saves the last element, shifts everything one slot right and drops the saved value at index 0. Repeat it k % n times (a full lap of n steps changes nothing).

Java
public void rotate(int[] nums, int k) {
    int n = nums.length;
    k %= n; // n rotations is a no-op
    for (int step = 0; step < k; step++) {
        int last = nums[n - 1];
        for (int i = n - 1; i > 0; i--) {
            nums[i] = nums[i - 1];
        }
        nums[0] = last;
    }
}

Simplest in-place idea, but up to 1010 moves at the limits.

At a glance

LevelApproachTimeSpace
Brute ForceRotate One Step, k TimesO(n·k)O(1)
BetterPlace Each Element via a CopyO(n)O(n)
OptimalThree ReversalsO(n)O(1)
Common pitfalls
  • Skipping k %= n — out-of-bounds reversals or wasted full laps.
  • Rotating left instead of right: the last k elements must come to the front.
  • Assigning nums = rotated in Java — that rebinds the local reference; the caller's array is unchanged.
Interview tips
  • Write out A·B → B·A on the board; the reversal proof is then one line.
  • Mention cyclic replacements (follow each element's chain, gcd(n,k) cycles) as another O(1)-space option.
  • Test k = 0, k = n and k > n explicitly.
Pattern
Reversal trick → swap two adjacent blocks of an array (or words in a string) in-place.
My notes saved in this browser