LeetCode 56: Merge Intervals is a Medium intervals problem. This Python walkthrough develops a sorted sweep 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 | Intervals |
| Reusable pattern | sorted sweep |
| Complexity | O(n log n) time and O(n) output space |
Recognizing the pattern
Sorting interval boundaries exposes a monotonic frontier: once an interval begins beyond it, earlier intervals cannot overlap again.
For this problem specifically, sort by start time and either extend the last merged interval or append a new disjoint interval. The invariant worth writing beside the code is: The output is sorted, disjoint, and exactly covers every processed interval.
Step-by-step algorithm
- Identify the input state consumed by
merge(intervals)and initialize the data required by the sorted sweep pattern. - Sort by start time and either extend the last merged interval or append a new disjoint interval.
- After each update, verify the page’s central invariant: The output is sorted, disjoint, and exactly covers every processed interval.
- Finish only after the boundary behavior is covered: Touching endpoints overlap under the problem definition.
Python solution
class Solution:
def merge(self, intervals):
intervals.sort(key=lambda pair: pair[0])
merged = []
for start, end in intervals:
if not merged or start > merged[-1][1]: merged.append([start, end])
else: merged[-1][1] = max(merged[-1][1], end)
return mergedReading the implementation
The main entry point is merge(intervals). The named working state includes merged; those variables make the sorted sweep 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, sort by start time and either extend the last merged interval or append a new disjoint interval.
Correctness argument
Initialization. Before the scan begins, the unresolved range contains every candidate and the processed range is empty, so no answer has been lost.
Preservation. Sort by start time and either extend the last merged interval or append a new disjoint interval. The chosen movement discards only candidates that cannot improve the answer; afterward, the output is sorted, disjoint, and exactly covers every processed interval.
Termination. A boundary advances on every iteration. Once the active range is exhausted, every viable candidate was either measured or safely eliminated, so the stored result is optimal.
Complexity and trade-offs
O(n log n) time and O(n) output space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.
Checking every pair avoids sorting but does quadratic work and complicates transitive overlaps. 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.
assert Solution().merge([[1,3],[2,6],[8,10],[15,18]]) == [[1,6],[8,10],[15,18]]Common mistakes and edge cases
- Problem-specific boundary: Touching endpoints overlap under the problem definition.
- Pattern-level pitfall: State whether touching endpoints count as overlap and preserve the appropriate endpoint when merging.
- Invariant check: after every update, confirm that the output is sorted, disjoint, and exactly covers every processed interval.
Interview review checklist
- Explain why sorted sweep matches the structure of this input.
- State the invariant in one sentence before tracing code: The output is sorted, disjoint, and exactly covers every processed interval.
- Derive O(n log n) time and O(n) output space from how many times each element or state is visited.
- Test the boundary explicitly: Touching endpoints overlap under the problem definition.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 228. Summary Ranges · Next: 57. Insert Interval