InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Two Pointers

Rotate Array

medium Original ↗ 00:00

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 straightforward: element `i` lands at index `(i + k) % n`. Can you get the same result 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.)

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug