The Runtime Theory
mediumleetcode#array#two-pointers

Rotate Array

Rotate an array to the right by k steps in place with O(1) space using three reversals of the whole array and its two halves.

The Runtime Theory Team1 min read
Solve it

solving happens on the judge — come back and mark it done

Sample cases

in[1,2,3,4,5,6,7], 3

out[5,6,7,1,2,3,4]

in[-1,-100,3,99], 2

out[3,99,-1,-100]

in[1,2], 3

out[2,1]

The machine must rotate an array right by k steps in place, with O(1) extra memory. The elegant trick: a right rotation is three reversals. Reverse the whole array, reverse the first k elements, reverse the rest. Three passes, no copies, and every element lands exactly where a naive shift would put it.

python
def rotate(nums, k):
    n = len(nums)
    k %= n
    nums.reverse()
    nums[:k] = reversed(nums[:k])
    nums[k:] = reversed(nums[k:])

Steps: (1) reduce k modulo n, (2) reverse the entire array, (3) reverse the first k elements, then the remaining n-k elements.

Time is O(n) — each element is touched by exactly two reversals. Space is O(1) (Python's slice above copies; a two-pointer swap loop keeps it truly in place).

Trickiest edge cases: k larger than n — k %= n handles it, e.g., rotating [1,2] by 3 is rotating by 1. k a multiple of n, or zero, leaves the array unchanged — skip the work entirely. Single-element arrays are unaffected by any k. The boundary between the two reversal chunks must fall at exactly the reduced k.

More practice in this topic

One dispatch a week

The trace behind each problem, the tradeoff that explains it, and one technical dispatch per week — no noise.

One technical dispatch per week. No noise.