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.
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.