Merge Intervals
O(n log n)
Sort by start; then walk once, extending the current interval whenever the next one overlaps it.
0/14 solved
Recognise it
The signal
A list of [start, end] pairs to merge, insert into, intersect, or check for overlap; calendar or meeting conflicts.
1Brute force
Compare every pair of intervals O(n2).
2The observation
Pairwise overlap checks: after sorting by start, only the last merged block can overlap the next interval.
3Why it works
With intervals sorted by start, the output so far is disjoint blocks and only the last block can still grow.
Reach for it when
- +A list of intervals/ranges to merge, insert into, or de-conflict.
- +'Meeting rooms', 'how many overlap', 'minimum to remove' — concurrency or conflict counting.
- +Two interval lists to intersect.
Not when
- ×Max number of non-overlapping intervals / min removalsuse Sort by **end**, greedy keep earliest end
- ×Count max simultaneous overlaps (meeting rooms)use Sweep over +1/-1 events, or min-heap of ends
- ×Many point-in-range increments, not whole-interval logicuse Difference array
- ×Intervals arrive online with queries in betweenuse Ordered set / balanced BST of intervals
- ×Ranges over a tiny fixed universeuse Counter array, bucket directly, skip the sort
- ×It's really a scheduling/greedy proof, not overlap geometryuse General greedy
Intuition
An interval is just a pair [start, end] — a meeting from 2 to 4, a booked seat range. Interval problems ask you to merge overlaps, insert a new one, or count how many overlap at once (meeting rooms).
Read the full intuition
The single move that unlocks almost all of them: sort by start time. Once sorted, overlaps can only happen between neighbours, so one left-to-right pass settles everything. Two intervals A then B overlap iff B.start <= A.end (B begins before A finishes).
Merge walk [[1,3],[2,6],[8,10]]:
- Take [1,3] as the current block.
- [2,6]: 2 ≤ 3 → overlap → extend end to max(3,6)=6 → block [1,6].
- [8,10]: 8 > 6 → no overlap → push [1,6], start new block [8,10].
- Result [[1,6],[8,10]].
Counting concurrent intervals (Meeting Rooms II) uses a twist: a min-heap of end times — pop a room when the next meeting starts after it ends; the heap's max size is the rooms needed.
Key idea
The reflex: see intervals → sort by start, then merge neighbours or sweep. If it's "how many at the same time", think heap of ends or a +1/−1 boundary sweep.
Why it costs what it costs
Time O(n log n). dominated by the sort; the merge sweep is linear.
Space O(n). the output list (and the heap for the rooms variant).
Practice
- Meeting RoomsFoundationFoundationPremiumEasy
- Merge IntervalsApply it · Merge all overlapping intervals.Apply itMeta, AmazonMedium
- Insert IntervalOne change · Input already sorted; insert one interval.One changeGoogle, AmazonMedium
- Interval List IntersectionsOne change · Two sorted lists instead of one.One changeMedium
- Non-overlapping IntervalsTwists · Select, do not merge.TwistsAmazon, GoogleMedium
- Meeting Rooms IIBranches · Count maximum concurrency.BranchesPremiumMedium
- Minimum Number of Arrows to Burst BalloonsBranches · Stab all intervals with fewest points.BranchesAmazon, UberMedium
- Data Stream as Disjoint IntervalsMastery checkMastery checkHard
- Movie FestivalCSESMedium
- Room AllocationCSESMedium
- Count Road Markers Covered by UbersUberOAEasy
- Social Distancing Groups (Partition Labels)NutanixOAMedium
- Count Integers in IntervalsHard
- Range ModuleHard
Pitfalls
Classic bugs
- !Forgetting to sort by start: the single-pass merge is only valid on sorted input.
- !Touching endpoints
[1,2],[2,3]: decide<=vs<per the problem statement; it changes the answer. - !Mutating
intervals[0]in place and returning it aliases the input: build a fresh result list. - !Meeting Rooms II: compare next start to the earliest end (heap top); pop only when
start >= earliestEnd. - !Assuming sort key doesn't matter: merging sorts by start, min-removal scheduling sorts by end.
Looks like it, isn't
- Non-overlapping Intervals needs Interval Scheduling (sort by end)
Why
You select intervals, not merge them: sort by end and greedily keep earliest finishers. - Minimum Number of Arrows to Burst Balloons needs Interval Scheduling (sort by end)
Why
Stabbing points uses the earliest-end greedy, not merging. - The Skyline Problem needs Sweep Line (events + active set)
Why
Overlaps must report max height per x: events + heap/multiset of active heights. - Minimum Interval to Include Each Query needs Offline Query Processing
Why
Nothing is merged. Sort the queries, push the intervals that start <= q into a min-heap by size, pop the ones that ended. source ↗
Go deepervariants and techniques · 2 combinations · resources
Variants and techniques
- Merge overlapsSort by start, extend or push. Merge Intervals.
- Insert oneAdd all before, merge the overlapping run, add all after. Insert Interval.
- Min removals / max non-overlapSort by end, greedily keep compatible ones. Non-overlapping Intervals.
- Concurrency countMin-heap of end times, or +1/-1 boundary sweep. Meeting Rooms II.
- Two-list intersectionTwo pointers; overlap = [max(starts), min(ends)] when valid. Interval List Intersections.
Combinations
Merge Intervals+Top-K Elements
minimum rooms/machines; assign rooms to customers
- Merge Intervals:
- sort by start
- Top-K Elements:
- min-heap of end times of active intervals
Merge Intervals+Ordered Set / Balanced BST (TreeMap, multiset)
add/remove/query ranges online (range module, count covered integers)
- Merge Intervals:
- the merge/split logic for overlapping ranges
- Ordered Set / Balanced BST (TreeMap, multiset):
- a TreeMap from start to end holds disjoint intervals with O(log n) neighbour lookup
Range ModuleCount Integers in IntervalsData Stream as Disjoint Intervals