LeetCode 88: Merge Sorted Array is an Easy array / string problem. This Python walkthrough develops a reverse two pointers 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 | Easy |
|---|---|
| Topic | Array / String |
| Reusable pattern | reverse two pointers |
| Complexity | O(m+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, compare the largest unused values and write into the final open slot of nums1. Working backward avoids overwriting values that have not been compared. The invariant worth writing beside the code is: Every position after the write pointer already contains the correct largest remaining value.
Step-by-step algorithm
- Identify the input state consumed by
merge(nums1, m, nums2, n)and initialize the data required by the reverse two pointers pattern. - Compare the largest unused values and write into the final open slot of nums1. Working backward avoids overwriting values that have not been compared.
- After each update, verify the page’s central invariant: Every position after the write pointer already contains the correct largest remaining value.
- Finish only after the boundary behavior is covered: Either input can be empty; equal values and duplicate runs are valid.
Python solution
class Solution:
def merge(self, nums1, m, nums2, n):
i, j, write = m - 1, n - 1, m + n - 1
while j >= 0:
if i >= 0 and nums1[i] > nums2[j]:
nums1[write] = nums1[i]
i -= 1
else:
nums1[write] = nums2[j]
j -= 1
write -= 1Reading the implementation
The main entry point is merge(nums1, m, nums2, n). The named working state includes i, j, write; those variables make the reverse two pointers state visible instead of hiding it in incidental control flow.
A single main loop advances the algorithm, which is the key reason the traversal does not revisit already resolved input unnecessarily. In concrete terms, compare the largest unused values and write into the final open slot of nums1. Working backward avoids overwriting values that have not been compared.
Correctness argument
Initialization. The data structure starts with exactly the information known before any input element is processed.
Preservation. Compare the largest unused values and write into the final open slot of nums1. Working backward avoids overwriting values that have not been compared. Each update records the current item without invalidating earlier decisions; consequently, every position after the write pointer already contains the correct largest remaining value.
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(m+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,0,0,0]; Solution().merge(nums,3,[2,5,6],3); assert nums == [1,2,2,3,5,6]Common mistakes and edge cases
- Problem-specific boundary: Either input can be empty; equal values and duplicate runs are valid.
- 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 every position after the write pointer already contains the correct largest remaining value.
Interview review checklist
- Explain why reverse two pointers matches the structure of this input.
- State the invariant in one sentence before tracing code: Every position after the write pointer already contains the correct largest remaining value.
- Derive O(m+n) time and O(1) extra space from how many times each element or state is visited.
- Test the boundary explicitly: Either input can be empty; equal values and duplicate runs are valid.
Browse the searchable 100 LeetCode Python Solutions hub. Next: 27. Remove Element