Learn the pattern · ~15 min
Merge Intervals
also called interval sorting, overlap merging
Sort intervals by start, then sweep once: each interval either stretches the last block or opens a new one.
Reach for it when you read
- +A list of ranges
[start, end]and the question is about overlap: merge them, find free time, total covered length. - +Insert a new range into a sorted, non-overlapping list.
- +"Can one person attend all meetings?", "do any two bookings clash?"
- +Two lists of ranges and you need where they intersect.
Not this one when
- ×Ranges add amounts that stack, like passengers or bookings: a difference array or line sweep.
- ×Keep the most non-overlapping intervals, or the fewest arrows: a greedy that sorts by end, not start.
- ×How many overlap at the busiest moment: a min-heap of end times or a +1/−1 sweep.
Learn Merge Intervals
First, what is an "interval"?
An interval [start, end] is a stretch of the number line: [2, 5] covers everything from 2 to 5, like a meeting from 2 o'clock to 5 o'clock.
Two intervals overlap when they share a point:
[1, 4]and[3, 6]share the stretch from 3 to 4: they overlap.[1, 2]and[5, 6]share nothing: a gap.[6, 8]and[8, 9]share only the point 8: they touch. Whether touching counts as overlapping depends on the problem, so watch for it.
In general, [a, b] and [c, d] overlap when c ≤ b and a ≤ d: each one starts before the other ends.
Merging a pile of intervals means replacing it with the fewest non-overlapping blocks that cover exactly the same points.
What does sorting by start buy us?
Here's the smallest question: can one person attend all these meetings? Meetings [9, 10], [1, 3], [4, 6], [5, 8]. Testing every pair works but is slow. Sort by start first:
[1, 3], [4, 6], [5, 8], [9, 10]
Now the rule is one line:
Compare each meeting only with the one just before it. If it starts before that one ends, they clash.
| meeting | previous ends at | what happens |
|---|---|---|
| [1, 3] | none | first meeting, nothing to compare |
| [4, 6] | 3 | 4 ≥ 3: starts after the last one ended, fine |
| [5, 8] | 6 | 5 < 6: starts while [4, 6] is still going: clash |
| [9, 10] | 8 | 9 ≥ 8: fine |
So the answer is no. After the sort, any clash shows up between neighbours, so one pass finds it. A meeting ending at 6 and one starting at 6 would be fine here: in Meeting Rooms, touching isn't a clash.
sort(iv.begin(), iv.end()); // by start
bool ok = true;
for (int i = 1; i < (int)iv.size(); i++)
if (iv[i][0] < iv[i - 1][1]) ok = false; // starts before the previous one endsYou don't need to memorise this. It's the table: sort, then compare with the one before.
Why is checking neighbours enough? Say meeting k clashes with some later meeting: it's still running when that one starts. The meeting right after k starts no later, so k is still running then too, and that neighbour pair clashes. If any pair clashes, some neighbours do.
Fine, but how does this help us?
The classic problem: Merge Intervals. Merge all overlapping intervals and return the blocks.
Take [8, 9], [1, 4], [12, 14], [2, 3], [6, 8], [3, 5] and solve it by hand. Draw each one on a number line and look for the gaps: nothing covers the stretch between 5 and 6, or the one between 9 and 12. Everything else is covered, in three unbroken pieces.
| covered stretch | made of | block |
|---|---|---|
| 1 to 5 | [1, 4], [2, 3], [3, 5] | [1, 5] |
| 6 to 9 | [6, 8], [8, 9] (they touch at 8) | [6, 9] |
| 12 to 14 | [12, 14] | [12, 14] |
The answer is [1, 5], [6, 9], [12, 14].
The brute force
Find any two intervals that overlap, glue them, and start over. Stop when no pair overlaps.
bool changed = true;
while (changed) {
changed = false;
for (int i = 0; i < (int)iv.size() && !changed; i++)
for (int j = i + 1; j < (int)iv.size() && !changed; j++)
if (iv[j][0] <= iv[i][1] && iv[i][0] <= iv[j][1]) {
iv[i] = {min(iv[i][0], iv[j][0]), max(iv[i][1], iv[j][1])};
iv.erase(iv.begin() + j);
changed = true;
}
}Each search is up to n²/2 pair checks, and there can be up to n − 1 merges, each followed by a new search: O(n³) in the worst case. Even the last search, which finds nothing, checks every pair: for n = 10⁵ that alone is 5 × 10⁹ checks. Time limit exceeded.
The one thought that fixes it
Sort by start: [1, 4], [2, 3], [3, 5], [6, 8], [8, 9], [12, 14]. Glue as you go, keeping only the last block in view.
Stop at [6, 8]. The block built so far is [1, 5], and 6 > 5: a gap.
Now think about every interval still to come. Each starts at 6 or later, because we sorted. And [1, 5] ends at 5. So nothing later can reach back into [1, 5]. That block is final: write it down and never look at it again.
That gives two cases for every interval, compared with the last block only:
- It starts after the block ends: a gap. The block is final; start a new one.
- It starts at or before the block ends: it overlaps. Stretch the block's end to the further of the two ends.
It's the same neighbour comparison as the meetings, except now you glue instead of reporting a clash.
sort(iv.begin(), iv.end()); // by start
vector<vector<int>> out;
for (auto& cur : iv) {
if (out.empty() || cur[0] > out.back()[1]) out.push_back(cur); // a gap: new block
else out.back()[1] = max(out.back()[1], cur[1]); // overlap: stretch it
}Why the max? [2, 3] sits inside [1, 4]. Setting the end to 3 would shrink the block to [1, 3] and lose the part from 3 to 4. On [1, 4], [2, 3], [4, 5] that mistake gives [1, 3], [4, 5] instead of [1, 5].
Dry run
| interval | vs the last block | what happens | blocks so far |
|---|---|---|---|
| [1, 4] | none | first: new block | [1, 4] |
| [2, 3] | 2 ≤ 4 | glue; end stays max(4, 3) = 4 | [1, 4] |
| [3, 5] | 3 ≤ 4 | glue; end becomes 5 | [1, 5] |
| [6, 8] | 6 > 5 | gap: [1, 5] is final, new block | [1, 5], [6, 8] |
| [8, 9] | 8 ≤ 8 | touching: glue; end becomes 9 | [1, 5], [6, 9] |
| [12, 14] | 12 > 9 | gap: new block | [1, 5], [6, 9], [12, 14] |
[1, 5], [6, 9], [12, 14], the same answer as the brute force.
[6, 8] and [8, 9] merged because the gap test is >. If touching intervals must stay apart, test >= instead: then the answer keeps [6, 8] and [8, 9] separate. Read the problem.
Why it's O(n log n)
The sort costs O(n log n). After it, count what happens to each interval: one comparison with the last block, then either a push or one max. That's O(n) for the pass. So O(n log n) in total, and the sort is the expensive part. Space: the output, plus whatever the sort uses.
From O(n³) down to O(n log n), because after sorting each block becomes final the moment a gap appears.
Already sorted? Insert Interval
Insert Interval gives you merged, sorted blocks and one new interval. No sort needed: copy every block that ends before the new one starts, glue every block that overlaps it (min of starts, max of ends), then copy the rest. That's O(n).
while (i < n && iv[i][0] <= nw[1]) { nw = {min(nw[0], iv[i][0]), max(nw[1], iv[i][1])}; i++; }Inserting [4, 7] into [1, 5], [6, 9], [12, 14] glues the first two: [1, 9], [12, 14].
Two lists? One pointer each
Interval List Intersections has two sorted lists of blocks. Keep one pointer in each. The overlap of the two current intervals is [max(starts), min(ends)], if that isn't empty. Then move the pointer whose interval ends first: it can't meet anything else.
[1, 5], [6, 9], [12, 14] against [3, 7], [9, 13] gives [3, 5], [6, 7], [9, 9], [12, 13].
Keep the most? Sort by end
Non-overlapping Intervals asks for the fewest removals so that the rest don't overlap. That's a different question: you're choosing which to keep, not gluing. Sort by end, and keep each interval that starts at or after the last kept end. The one that ends earliest leaves the most room. Our six intervals need one removal, [1, 4].
How many at once? A heap of end times
Meeting Rooms II asks for the most meetings running at the same moment. Sort by start and keep a min-heap of end times: pop every meeting that has ended, push the new one. The largest heap size is the answer. Our six intervals need 2 rooms.
Remember this
- "Overlapping ranges", "merge", "insert", "free time", "total covered": sort by start, compare with the last block only.
- Stretch with
max(end, cur end): a short interval can sit inside a long one. >or>=decides whether touching intervals merge. Read the problem.- To keep the most intervals (fewest removals, fewest arrows), sort by end instead.
- Whenever a problem asks "which of these ranges overlap?", sort them first.
Practise it on Meeting Rooms (any clash), then Merge Intervals, Insert Interval (already sorted), Interval List Intersections (two lists), Non-overlapping Intervals (sort by end) and Meeting Rooms II (how many at once).
Below, watch Merge Intervals run line by line.
Watch it work, line by line
Merge Intervals ↗, [[2,6], [9,11], [1,3], [10,12], [5,7]] → [[1,7], [9,12]]. Step with → and ←. The data is on the left, the code and the variables that changed on the right, and 3 times it stops to ask you what happens next.
When to use it, and when not
Ask yourself
Am I given [start, end] ranges and asked to combine overlapping ones (merge, insert, total covered, any conflict)? Then sort by start and only look at the last block.
Reach for it when
- +list of [start, end] pairs
- +merge, insert, intersect, or detect overlap
- +calendar / meeting conflicts
- +n up to 1e5; sort is fine
It fails 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
Looks like it, isn't (and the other way round)
- Non-overlapping Intervals looks like Merge Intervals, needs Interval Scheduling (sort by end)
You select intervals, not merge them: sort by end and greedily keep earliest finishers.
- Minimum Number of Arrows to Burst Balloons looks like Merge Intervals, needs Interval Scheduling (sort by end)
Stabbing points uses the earliest-end greedy, not merging.
- The Skyline Problem looks like Merge Intervals, needs Sweep Line (events + active set)
Overlaps must report max height per x: events + heap/multiset of active heights.
- Minimum Interval to Include Each Query looks like Merge Intervals, needs Offline Query Processing
Nothing is merged. Sort the queries, push the intervals that start <= q into a min-heap by size, pop the ones that ended.
Recall card
Answer each one out loud before you open it. Come back in three days and try again without reading the page.
1Why does merging sort by start, and what goes wrong without the sort?Reveal
Sorted by start, the next interval can only overlap the last block, so one pass works. Unsorted, a later interval can overlap any earlier block and the single pass misses merges.
2Why
max(last.end, cur.end)and notcur.end?RevealA nested interval like
[2,3]inside[1,10]would shrink the block to[1,3].3Which interval problems sort by end instead?Reveal
Keeping the most non-overlapping intervals, or the fewest removals or arrows: greedy, keep the earliest-ending one each time.
Practice ladder
- 1Meeting Roomsany conflictEasy
- 2Merge Intervalsthe hookMedium
- 3Insert Intervalinsert oneMedium
- 4Interval List Intersectionstwo listsMedium
- 5Count Road Markers Covered by Uberscount, don't listEasy
- 6Non-overlapping Intervalssort by endMedium
- 7Meeting Rooms IIhow many at onceMedium
- 8Data Stream as Disjoint Intervalslive insertsHard
Finished Merge Intervals? Mark it done and Lessgo moves you to the next step.