Merge overlapping [start, end] intervals by sorting on start and sweeping once in O(n log n). Touching intervals merge too. Asked everywhere, run it live.
The problem
Merge all overlapping intervals and return them sorted by start. Intervals that touch ([1, 4] and [4, 5]) also merge.
Examples
Example 1
Input
merge_intervals([[1, 3], [2, 6], [8, 10], [15, 18]])
Expected output
[[1, 6], [8, 10], [15, 18]]
Example 2
Input
merge_intervals([[1, 4], [4, 5]])
Expected output
[[1, 5]]
+ 3 hidden tests on Submit — containment, unsorted input.
Edge cases to ask about
- Containment
- Touching intervals
- Unsorted input
Hints
0/3How an interviewer scores this
0/9Your code runs in real CPython inside your browser — nothing is sent anywhere. The first run downloads the interpreter (about 6 MB, once). Your code is saved on this device as you type.
Complexity Lab
What does this cost as n grows?
Interviewers score the analysis as much as the code. Commit to an answer first — then check it, and measure your code against the optimal one at growing input sizes.
Pick both to reveal the answer.
Measure it
Runs the function on inputs of size 250 up to 16,000 and records the time and peak memory. Slow solutions stop early — a short curve is itself the answer.
From brute force to optimal
The progression an interviewer wants to hear, one step at a time.
| Approach | Time | Space | Idea |
|---|---|---|---|
| Sort by start, sweep | O(n log n) | O(n) | After sorting, an overlap can only be with the last merged interval. |
Walkthrough of the optimal approach (try it yourself first)
Sort by start. Walk the intervals: if the current one starts at or before the end of the last merged interval, extend that end with max (it might be fully contained); otherwise start a new merged interval.
Complexity: O(n log n) time, O(n) space. Sorting dominates; the sweep is linear.
Reveal the reference solution
def merge_intervals(intervals): merged = [] for start, end in sorted(intervals): if merged and start <= merged[-1][1]: merged[-1][1] = max(merged[-1][1], end) else: merged.append([start, end]) return merged
Follow-ups interviewers ask
- Insert one new interval into a sorted, merged list in O(n).
Frequently asked interview questions
Core interview concepts, complexities, and follow-ups scored by hiring teams.
What is the time complexity of Merge Overlapping Intervals in Python?
The optimal solution runs in O(n log n) time and O(n) auxiliary space. Sorting dominates; the sweep is linear.
What follow-up questions do interviewers ask about Merge Overlapping Intervals?
Insert one new interval into a sorted, merged list in O(n).
