InterviewPrepKit

Home / Coding / Two Pointers

Rotate Array

medium Original β†—
Solving tips
  • Always normalize k %= n first, since k can exceed the array length and the modulo makes the rotation well-defined.
  • The interview-grade in-place answer is triple reversal: reverse the whole array, reverse the first k, then reverse the last n-k, in O(n) time and O(1) space.
  • Know the alternatives to name: an extra array using i -> (i+k)%n is trivial O(n) space, and the cyclic juggling walk is O(1) space but needs a placed-counter over gcd(n,k) cycles.
  • Pitfall: mutate in place with nums[:]=result, never nums=result (rebinds the local name); and for a right rotation the block order is whole -> first k -> last n-k.

Problem

Given an integer array nums, rotate it to the right by k steps, in place. Rotating right by one step moves the last element to the front; rotating by k does that k times. k can be larger than the array length.

The function returns nothing β€” mutate nums directly.

Examples

Example 1

Input:  nums = [1, 2, 3, 4, 5, 6, 7], k = 3
Output: nums = [5, 6, 7, 1, 2, 3, 4]

The last three elements wrap around to the front.

Example 2

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

Two right rotations: [99, -1, -100, 3] then [3, 99, -1, -100].

Example 3

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

k = 5 on length 2 is the same as k = 5 % 2 = 1.

Constraints

  • 1 <= nums.length <= 10^5
  • -2^31 <= nums[i] <= 2^31 - 1
  • 0 <= k <= 10^5
  • Follow-up: O(1) extra space, and there are at least three different ways to do it.

Think about it first

Hint 1 First normalize: rotating by `k` is the same as rotating by `k % n`. What happens if you forget this and `k > n`?
Hint 2 With O(n) extra space it's trivial: element `i` lands at index `(i + k) % n`. Now β€” can you get the same final picture using only reversals?
Hint 3 Reverse the whole array, then reverse the first `k` elements, then reverse the remaining `n - k`. Each element is swapped at most twice and no extra memory is needed. (A cycle-following "juggling" walk also works: keep placing each element at `(i + k) % n` until you return to start, and repeat from the next index if cycles don't cover everything.)
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.