LeetCode 189: Rotate Array is a Medium array / string problem. This Python walkthrough develops a three reversals solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.
This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.
| Difficulty | Medium |
|---|---|
| Topic | Array / String |
| Reusable pattern | three reversals |
| Complexity | O(n) time and O(1) extra space |
Recognizing the pattern
Array and string questions usually reward a precise index invariant. Decide which prefix or suffix is already final before mutating the next position.
For this problem specifically, normalize k, reverse the whole array, then reverse the two rotated segments. Reversal moves both groups into their final cyclic order. The invariant worth writing beside the code is: After the three reversals, each original index maps to (index + k) modulo n.
Step-by-step algorithm
- Identify the input state consumed by
rotate(nums, k)and initialize the data required by the three reversals pattern. - Normalize k, reverse the whole array, then reverse the two rotated segments. Reversal moves both groups into their final cyclic order.
- After each update, verify the page’s central invariant: After the three reversals, each original index maps to (index + k) modulo n.
- Finish only after the boundary behavior is covered: Reduce k modulo the length; an empty array and k equal to zero need no work.
Python solution
class Solution:
def rotate(self, nums, k):
if not nums:
return
k %= len(nums)
nums.reverse()
nums[:k] = reversed(nums[:k])
nums[k:] = reversed(nums[k:])Reading the implementation
The main entry point is rotate(nums, k). The implementation keeps little named state because each operation can be resolved directly from the current input position.
The method expresses the transformation directly without a general traversal loop. In concrete terms, normalize k, reverse the whole array, then reverse the two rotated segments. Reversal moves both groups into their final cyclic order.
Correctness argument
Initialization. The data structure starts with exactly the information known before any input element is processed.
Preservation. Normalize k, reverse the whole array, then reverse the two rotated segments. Reversal moves both groups into their final cyclic order. Each update records the current item without invalidating earlier decisions; consequently, after the three reversals, each original index maps to (index + k) modulo n.
Termination. The traversal consumes a finite input or finite state space. At the end, the invariant covers the complete input, which is precisely the condition required for the returned result.
Complexity and trade-offs
O(n) time and O(1) extra space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.
A copied output buffer can simplify reasoning, but the in-place version reduces auxiliary memory when mutation is allowed. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.
Regression check
The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.
One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.
nums=[1,2,3,4,5,6,7]; Solution().rotate(nums,3); assert nums == [5,6,7,1,2,3,4]Common mistakes and edge cases
- Problem-specific boundary: Reduce k modulo the length; an empty array and k equal to zero need no work.
- Pattern-level pitfall: Do not let a write operation destroy input that a later read still needs; write direction and boundary conventions matter.
- Invariant check: after every update, confirm that after the three reversals, each original index maps to (index + k) modulo n.
Interview review checklist
- Explain why three reversals matches the structure of this input.
- State the invariant in one sentence before tracing code: After the three reversals, each original index maps to (index + k) modulo n.
- Derive O(n) time and O(1) extra space from how many times each element or state is visited.
- Test the boundary explicitly: Reduce k modulo the length; an empty array and k equal to zero need no work.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 169. Majority Element · Next: 121. Best Time to Buy and Sell Stock