Sort closed intervals by start so each new interval only needs comparison with the final merged frontier. Preserve the furthest end through nested ranges, and distinguish union construction from concurrency counting.
Recognize it when The output is the union of overlapping closed intervals, including touching endpoints.
Checking your account…
Merge Intervals Code Labs
Let Sorting Finish Earlier Groups
If interval starts arrive arbitrarily, a later input may overlap a block already considered finished. Sorting by start prevents that surprise. Once a new start is beyond the current merged end, no later start can reach back into that finished group, so the scan needs only the final output interval as its active frontier.
Extend the Furthest End, Not the Latest End
These Labs use closed intervals: touching endpoints belong to one union block. A nested interval may end earlier than the frontier already reached; replacing the end with its own endpoint would lose covered points. Use max to extend or retain the current end. The trace records separately copied merged lists after each sorted input.
Trace Interval Merges
Reference
def merge_trace(intervals):
merged=[]
trace=[]
for start,end in sorted(intervals):
if not merged or start > merged[-1][1]:
merged.append([start,end])
else:
merged[-1][1]=max(merged[-1][1],end)
trace.append([item.copy() for item in merged])
return trace
Practice
Implement merge_trace(intervals). Sort by start and return the merged list after each input interval is consumed. Intervals are closed [start, end] pairs with start <= end; touching endpoints merge.
Public tests
Make overlap local after sorting
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
Trace Interval Merges
def merge_trace(intervals):
merged=[]
trace=[]
for start,end in sorted(intervals):
if not merged or start > merged[-1][1]:
merged.append([start,end])
else:
merged[-1][1]=max(merged[-1][1],end)
trace.append([item.copy() for item in merged])
return trace
Preserve a Nested End and Merge a Touching Start
Run the existing closed-interval trace on [[4, 6], [1, 4], [2, 3]]. Sorting exposes nesting before the touching endpoint.
Step
Executed statement
State
Why
Order starts
for start,end in sorted(intervals):
order=[[1,4],[2,3],[4,6]]
A completed earlier group cannot be reached by a later smaller start.
Seed first group
merged.append([start,end])
merged=[[1,4]]
There is no active group to compare yet.
Snapshot
trace.append([item.copy() for item in merged])
trace=[[[1,4]]]
Copied endpoints keep this observation stable after later extensions.
Consume nested [2,3]
merged[-1][1]=max(merged[-1][1],end)
merged=[[1,4]]
The nested interval cannot shrink the already covered endpoint 4.
Consume touching [4,6]
merged[-1][1]=max(merged[-1][1],end)
4 > 4 is False; merged becomes [[1,6]]
Closed endpoint equality follows the merge branch.
Return snapshots
return trace
[[[1,4]],[[1,4]],[[1,6]]]
The output shows the frontier after each sorted interval.
Print
Output
print(merge_trace([[4, 6], [1, 4], [2, 3]]))
[[[1, 4]], [[1, 4]], [[1, 6]]]
Reuse Sorted Disjoint Input for Insertion
The insertion Lab first copies intervals ending before the new start, then grows the inserted union through all overlapping starts, and finally copies the remaining suffix. It does not sort again because its input contract already supplies sorted disjoint intervals. An interval touching the growing end is included by the closed <= comparison.
Insert and Merge an Interval
Reference
def insert_interval(intervals, new_interval):
result=[]
start,end=new_interval
index=0
while index<len(intervals) and intervals[index][1] < start:
result.append(intervals[index].copy()); index+=1
while index<len(intervals) and intervals[index][0] <= end:
start=min(start,intervals[index][0]); end=max(end,intervals[index][1]); index+=1
result.append([start,end])
result.extend(item.copy() for item in intervals[index:])
return result
Practice
Implement insert_interval(intervals, new_interval). intervals is sorted and disjoint. Return the merged result without mutating inputs. Intervals are closed [start, end] pairs with start <= end; touching endpoints merge.
Public tests
Merge touching overlaps without mutation
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
Insert and Merge an Interval
def insert_interval(intervals, new_interval):
result=[]
start,end=new_interval
index=0
while index<len(intervals) and intervals[index][1] < start:
result.append(intervals[index].copy()); index+=1
while index<len(intervals) and intervals[index][0] <= end:
start=min(start,intervals[index][0]); end=max(end,intervals[index][1]); index+=1
result.append([start,end])
result.extend(item.copy() for item in intervals[index:])
return result
Keep Union and Concurrency Separate
One merged range does not reveal whether one or five original intervals covered a position. A sweep line preserves start/end events when counts or peak activity are the answer. Half-open scheduling has different touching semantics; convert the comparison deliberately instead of reusing a closed-union condition unchanged.
State Mutation and Observation Costs in an Interview
Sorting and one union scan cost O(n log n); insertion into sorted disjoint input is O(n). The trace additionally copies every current merged block after each input and can cost O(n²) on disjoint intervals. Output lists must not alias mutable caller intervals when the contract promises no mutation. Explain a nested interval and a touching endpoint before claiming the frontier is complete.
Template To Memorize
Learn this shape by heart; most problems in this family change only one or two lines of it.
Sort and merge intervals
Sort by start; overlap extends, gap appends.
You work with ranges [start, end] that may overlap.
Trigger words
intervals
overlapping
meeting rooms
insert interval
non-overlapping
start and end times
def merge(intervals):
merged = []
for start, end in sorted(intervals):
if merged and start <= merged[-1][1]: # overlaps the last interval
merged[-1][1] = max(merged[-1][1], end)
else:
merged.append([start, end])
return merged
After sorting by start, an interval can only overlap the last merged one.
Decide whether touching ends (end == start) count as overlapping for each problem.
How problems bend it
Minimum removals so none overlap: Same sort by start; on overlap count one removal and keep the smaller end, because the interval that ends first leaves the most room.
How many rooms are needed: Turn each interval into (start, +1) and (end, -1) events, sort them, and keep a running sum; its peak is the answer. A min-heap of end times also works.
Python Version Note
Python 3.11+
sorted() creates a new outer sequence, but nested input lists are still shared unless copied before mutation; a shallow outer copy alone does not isolate interval endpoints.
Interview bounds depend on the stated representation, input model, and real Python operations.
Operation
Average
Worst
Interview note
Sort and scan closed interval union
O(n log n)
O(n log n)
The merge-trace Lab sorts once; its scan is linear but copied snapshots make its total O(n²) worst case on disjoint intervals.
Space
O(n) copied union output; the merge trace may store O(n²) interval snapshots.
Assumptions
The insertion Lab assumes sorted disjoint list pairs and scans O(n), copying output without mutating the caller. Closed ranges satisfy start <= end and touching endpoints merge.
sorted() creates a new outer sequence, but nested input lists are still shared unless copied before mutation; a shallow outer copy alone does not isolate interval endpoints.
Invariants Worth Saying Aloud
Merged output is sorted and disjoint under closed-interval semantics; only its last block can overlap the next sorted interval.
The current end is the maximum end of all intervals in the active merged group, so nested ranges cannot shrink it.
When To Use Or Avoid Merge Intervals
Use It When
Merge unsorted closed ranges after sorting once.
Insert a new closed range into already sorted disjoint ranges with one linear scan and copied output.
Choose Another Tool When
Use a sweep line when overlap counts or peak concurrency matter; merging loses multiplicity.
Choose a strict comparison for half-open scheduling ranges when touching boundaries must stay separate; these Labs use closed intervals.
Common Pitfalls
These are the mistakes most likely to survive a happy-path example and fail a boundary case.
01
Shrinking the frontier for a nested interval
After [1, 8], consuming [2, 3] must retain coverage through 8; direct assignment drops the outer interval tail.
Prevent it: Use max(current_end, incoming_end) when merging an overlap.