Question presented to candidate:
"Given a Python list nums and a non-negative integer k, rotate the list to the right by k steps, in place. For example [1, 2, 3, 4, 5, 6, 7] with k = 3 becomes [5, 6, 7, 1, 2, 3, 4]. Can you do it with O(1) extra space?"
What a strong answer should cover:
- Reduce
k %= nfirst (k can exceed n) and guard the empty list. - The brute force (rotate by one, k times, O(nยทk)) and the extra-array version (O(n) space), then the three-reversal algorithm: O(n) time, O(1) space.
- Why the reversals work:
A Bโrev(B) rev(A)โB A. - Optionally cyclic replacements, and why they may need
gcd(n, k)separate cycles. - Python specifics:
nums[:] = nums[-k:] + nums[:-k]mutates the caller's list but uses O(n) extra space, plainnums = ...only rebinds a local name,collections.deque.rotate(k)exists, and Python's%is never negative for a positive n.
Clarifying questions expected:
- "Right or left rotation, and can k be larger than n or negative?"
- "Must it be in place, or may I return a new list?"
Code / implementation expected: Yes โ a Python function that rotates nums in place with three reversals.