Merge Intervals
Sort intervals by start and sweep once, extending the current interval while the next one overlaps and emitting it when a gap appears.
You have not marked these as done yet. Read on anyway if they feel familiar; come back to them if something here does not land.
Overview
Given a list of [start, end] intervals, return the minimal list of disjoint intervals covering the same points. After sorting by start, overlapping intervals are adjacent, so a single pass suffices: keep a current interval; if the next interval starts at or before current.end, extend current.end = max(current.end, next.end); otherwise emit current and begin a new one.
The pattern generalizes to almost every interval question — insert an interval, intersect two lists, count rooms, find free time — by changing what happens at overlap and at gap. The sort is what makes greedy correct; on unsorted input a later interval can bridge two earlier ones.
Intuition
A mental model before the formal terms.
Lay the intervals as strips of tape on a number line, then walk left to right. As long as the next strip starts before the tape you are currently holding ends, it just makes that tape longer. The first time you see daylight between the tape and the next strip, you tear off the tape and start a new one.
How it works
- Sort intervals by start (ties by end are irrelevant).
- Initialize
current = intervals[0]. - For each subsequent
[s, e]: ifs ≤ current.end, setcurrent.end = max(current.end, e). Else pushcurrentto the output and setcurrent = [s, e]. - Push the final
current. Uses < current.endinstead of≤if touching intervals must stay separate.
Why it works
Invariant: after processing the first k sorted intervals, the output plus current is exactly the union of those k intervals as disjoint pieces, with current being the piece with the largest start.
Greedy-choice / exchange. Because intervals are sorted by start, the next interval starts at or after current.start. If it overlaps current, its union with current is a single interval, so merging is forced — no optimal output could keep them apart. If it does not overlap, it starts after current.end and, since all later intervals start even later, nothing can ever extend current again; emitting it is safe. Either way the choice is the only one consistent with any correct output.
The output is minimal because consecutive emitted intervals are separated by a genuine gap that no input interval covers.
Recognition
How to tell a problem wants this.
- "Merge overlapping intervals", "union of ranges", "total covered length", "insert a new interval into a sorted list".
- Any question where sorting by start and scanning with a running
endis the natural model: free time between meetings, employee schedules, interval intersections. - Input up to
10^5intervals —O(n log n)sort-and-sweep is the target.
Interactive visualization
Play, step, change the input. ← → and space work too.
| id | start | end | state |
|---|---|---|---|
| A | 1 | 3 | — |
| B | 3 | 5 | — |
| C | 4 | 6 | — |
| D | 9 | 11 | — |
| E | 12 | 15 | — |
| F | 8 | 10 | — |
1sort intervals by start time2out = []3cur = the first interval4for (s, f) in the rest:5 if s <= cur.end: # overlapping, or merely touching6 cur.end = max(cur.end, f) # absorb it, extend the accumulator7 else:8 out.append(cur); cur = (s, f) # a real gap: flush and restart9out.append(cur)10return outPseudocode
1sort intervals by start2out = []; cur = intervals[0]3for [s, e] in intervals[1:]:4 if s <= cur.end: cur.end = max(cur.end, e)5 else: out.push(cur); cur = [s, e]6out.push(cur)7return outImplementations
1# Merge intervals: sort by start, then sweep once extending the current2# interval while the next one overlaps, emitting when a gap appears.3# CONVENTION: closed real intervals [start, end]. Touching merges ([1,3] and4# [3,6] become [1,6]) but merely adjacent does not ([1,3] and [4,6] stay5# separate). gaps() and covered_length() use the same convention, so a gap is6# the open span between two covered ranges and a length is end - start.7 8 91 · Sort by start; the sweep depends entirely on that ordering10def merge(iv: list[tuple[int, int]]) -> list[tuple[int, int]]:11 if not iv:12 return []13 ordered = sorted(iv) # tuples compare lexicographically: start, then end14 15 out: list[list[int]] = [list(ordered[0])]16 for s, e in ordered[1:]:172 · Overlap (or touch) means extend the current end; otherwise emit18 if s <= out[-1][1]:19 out[-1][1] = max(out[-1][1], e)20 else:21 out.append([s, e])22 return [(s, e) for s, e in out]23 24 253 · Inserting one interval into an already-merged list is a three-phase scan26def insert(sorted_iv: list[tuple[int, int]], add: tuple[int, int]) -> list[tuple[int, int]]:27 out: list[tuple[int, int]] = []28 lo, hi = add29 i = 030 n = len(sorted_iv)31 # everything strictly before the new interval32 while i < n and sorted_iv[i][1] < lo:33 out.append(sorted_iv[i])34 i += 135 # everything overlapping it, absorbed into (lo, hi)36 while i < n and sorted_iv[i][0] <= hi:37 lo = min(lo, sorted_iv[i][0])38 hi = max(hi, sorted_iv[i][1])39 i += 140 out.append((lo, hi))41 # everything strictly after42 out.extend(sorted_iv[i:])43 return out44 45 464 · The complement: the uncovered gaps within [lo, hi], same convention47def gaps(merged: list[tuple[int, int]], lo: int, hi: int) -> list[tuple[int, int]]:48 out: list[tuple[int, int]] = []49 cursor = lo50 for s, e in merged:51 if s > cursor:52 out.append((cursor, s))53 cursor = max(cursor, e)54 if cursor < hi:55 out.append((cursor, hi))56 return out57 58 595 · Total covered length, which merging makes a trivial sum60def covered_length(merged: list[tuple[int, int]]) -> int:61 return sum(e - s for s, e in merged)sorted(iv)needs no key: tuples compare lexicographically, so(start, end)order comes for free — the one language here where the default is exactly right.- The working list holds *lists* rather than tuples because the sweep mutates
out[-1][1]; the final comprehension converts back to tuples for an immutable result. for s, e in ordered[1:]unpacks in the loop header, though the slice copies —itertools.islice(ordered, 1, None)avoids that for large inputs.out.extend(sorted_iv[i:])appends the entire tail in one call, which is faster than a loop.sum(e - s + 1 for s, e in merged)is the covered length as a one-line generator.
The ordered[1:] slice is an extra O(n) copy; islice removes it without changing the loop.
- Tuple lexicographic comparison makes
sorted(iv)correct with no key, which is a genuine convenience over the other three languages. - Tuples are immutable, so the in-place extension needs lists — converting back at the end keeps the public type immutable.
list.extend(iterable)is a single C-level call and beats a Python loop ofappend.ordered[1:]copies;itertools.islice(ordered, 1, None)is the lazy alternative.
- Trying to mutate a tuple in the sweep (
out[-1][1] = ...on a tuple), which raisesTypeError. - Slicing in the loop header on a very large list and doubling memory.
- Assuming
sorted(iv)sorts only by start — it also orders by end, which here is harmless and occasionally relied upon.
- Sorting pairs by start-then-end is free in C++ (
std::pairdefault ordering) and Python (tuple ordering), needs an explicit two-key comparator in JS/TS, and in JavaScript the default is actively wrong because it stringifies. - Mutability of the accumulator differs: C++
pairand JS/TS arrays are mutable in place, while Python tuples are not — so the Python version sweeps over lists and converts back. - TypeScript tuple spreading widens to
number[], so output tuples must be built by explicit indexing — a friction the other three do not have. - Appending a tail: Python
list.extend(slice)is one call, C++ needsinsertwith iterators, and JS/TS need a loop or a spread.
Complexity
Sorting dominates; O(n) if already sorted by start (the Insert Interval variant). Output excluded, O(log n) for in-place sort.
Compare growth rates in the Complexity Explorer →When to use — and when not to
- Union, coverage length, or gaps of a set of intervals.
- Insert Interval: input already sorted — skip the sort and do the linear sweep.
- Pre-processing before other interval logic (e.g. checking if a query range is fully covered).
- Skipping the sort:
[[1,4],[5,6],[2,5]]in input order gives[1,4]then[5,6]then[2,5]cannot merge back into the emitted[1,4], producing three intervals; sorted, the answer is one interval[1,6]. Greedy without the sort is wrong, not just slow. - Counting overlap depth (rooms needed) — merging loses the multiplicity; use Interval Scheduling with a heap or a +1/−1 sweep.
- Dynamic inserts and deletes with queries in between — maintain an ordered set / balanced tree of disjoint intervals or a Segment Tree instead of re-merging each time.
Alternatives
Common mistakes
- Extending with
cur.end = einstead ofmax(cur.end, e)— a short interval inside a long one shrinks the merged result. - Comparing against the wrong element (the next input interval instead of the last output interval).
- Wrong boundary convention (
<vs≤) for touching intervals. - Mutating the input intervals when the caller still needs them.
Interview patterns
- Merge Intervals, Insert Interval, Interval List Intersections (two-pointer variant over two sorted lists).
- Employee Free Time: merge all schedules, then output the gaps.
- Meeting Rooms I: after sorting, any overlap between neighbours means one person cannot attend all.
- Merge IntervalsIntermediate
Example problems
Check yourself
Answer out loud or on paper first, then compare. These come from the interview questions linked to this lesson.
A problem looks like it could be greedy. How do you decide whether greedy is correct or whether you need DP?
Show a strong answerHide the answer
Greedy is correct only if the problem has the greedy-choice property: some locally optimal choice is guaranteed to be part of *some* globally optimal solution, and after making it the remaining problem is a smaller instance of the same kind. Both greedy and DP need optimal substructure; the difference is that DP considers every choice at each state and greedy commits to one. So the question is really: can I prove that one specific choice is always safe?
The tool for that proof is the exchange argument: take any optimal solution that does not make the greedy choice, swap in the greedy choice, and show the result is no worse. In Interval Scheduling, picking the interval that ends earliest is safe because any optimal solution's first interval can be replaced by the earliest-ending one without breaking compatibility with the rest. If the exchange argument does not go through, greedy is suspect. The other tool is counterexample hunting: try small adversarial inputs. Coin Change with coins
{1, 3, 4}and amount6— greedy gives4+1+1, optimum is3+3. That one example kills the greedy for arbitrary denominations, though it works for canonical systems like US coins.A strong candidate knows the sibling pairs: Fractional Knapsack is greedy by value density, 0/1 Knapsack is not (density greedy fails when a low-density item fills the capacity exactly); Activity Selection greedy by earliest finish works, weighted interval scheduling needs DP; minimum spanning tree greedy (Kruskal's Algorithm) works because of the cut property, shortest path with negative edges does not. When unsure in an interview, they say so, write the DP (always correct if the state is right), and note that a greedy would be an optimization to prove later — that ordering is the mark of an engineer who values correctness over cleverness.
Full interview question, with follow-ups and red flags →You have written an algorithm. How do you convince me it is correct without running it on every input?
Show a strong answerHide the answer
Testing shows the algorithm works on the inputs tried; a proof shows it works on all of them. A strong candidate matches proof technique to code shape. Loops → invariants. State a property that holds before the first iteration, is preserved by each iteration, and at termination implies the result. For Binary Search: "the target, if present, lies in
[lo, hi]" — true initially, preserved by each discard because of sortedness, and whenlo > hithe range is empty so the target is absent. For Two Pointers (Opposite Ends): "every solution pair lies within[l, r]". For Kadane's Algorithm: "curis the maximum sum of a subarray ending ati". An invariant that cannot be stated precisely is a signal the algorithm might be wrong.Recursion and DP → induction. Assume the recursive calls return correct answers for smaller inputs and show the combination is correct; the base case anchors it. For DP, the induction is over the topological order of states: "
dp[i]is correct assumingdp[j]is correct for alljit depends on". Greedy → exchange argument. Show any optimal solution can be transformed into the greedy one without losing optimality; if the exchange cannot be made, look for the counterexample that the failed exchange suggests. Graph algorithms → structural lemmas. BFS layers equal distances by induction on distance; Dijkstra's correctness rests on the lemma that the minimum tentative node has its final distance, which holds only with non-negative weights.They also use reduction: "this is exactly interval scheduling, whose greedy is known optimal", which transfers a known proof. And they complement the proof with disciplined edge-case enumeration — empty input, single element, all equal, extreme values, the boundary of every
Full interview question, with follow-ups and red flags →<vs<=— because a proof covers the algorithm while edge cases catch the gap between the algorithm and the code. Finally, they say what they are *not* sure of: "I believe the invariant holds when duplicates are present, let me check the<=branch." That honesty is itself evidence of correctness-oriented thinking.Prove earliest-finish-first is optimal for interval scheduling.
Show a strong answerHide the answer
Let
Full interview question, with follow-ups and red flags →Obe optimal with first intervalo_1; greedy picksg_1withend(g_1) ≤ end(o_1). Replacingo_1byg_1keepsOfeasible and the same size. Induct on the remainder afterend(g_1).