Coalesce Overlapping Closed Intervals
Easy · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Given an arbitrarily ordered list of closed intervals [start, end] with integer endpoints, merge every group of intersecting intervals into a single [min_start, max_end] interval and return the resulting non-overlapping intervals ordered by ascending start.
def merge_intervals(intervals: list[list[int]]) -> list[list[int]]:
Follow these exact rules:
- Every
[start, end]satisfiesstart <= endand represents the closed continuous interval containingstart,end, and all real numbers between them. - Two intervals intersect whenever they share at least one real number. Intervals that meet at a single endpoint—such as
[2, 6]and[6, 9], or[8, 8]and[8, 11]—share that boundary point and must be merged. - Intervals separated by an uncovered real open gap—such as
[0, 5]and[6, 8]—share zero points (for example,5.5lies in neither interval) and must remain separate, even though no integer sits strictly between5and6. - Merging is transitive: whenever intervals are connected by a chain of pairwise overlaps (
I_1intersectsI_2andI_2intersectsI_3), collapse the entire chain into one interval[smallest_start, largest_end]covering the exact same set of real points. - Duplicate intervals, single-point intervals (
start == end), and intervals strictly nested inside wider intervals may appear in the input. - Return the merged disjoint intervals sorted in strictly increasing order of
start, without mutating the caller's input list or sublists.
Examples
Example 1
Input: intervals = [[10, 14], [2, 8], [4, 6], [12, 18]]
Output: [[2, 8], [10, 18]]
[4, 6] lies completely inside [2, 8], leaving [2, 8]. [10, 14] and [12, 18] overlap across [12, 14] and coalesce into [10, 18].
Example 2
Input: intervals = [[6, 8], [0, 5], [8, 8], [8, 11]]
Output: [[0, 5], [6, 11]]
[0, 5] and [6, 8] stay separate because real numbers strictly between 5 and 6 are uncovered. [6, 8], [8, 8], and [8, 11] all share point 8 and combine into [6, 11].
Example 3
Input: intervals = [[-8, -3], [-4, 1], [-8, -3], [3, 5]]
Output: [[-8, 1], [3, 5]]
Both copies of [-8, -3] intersect [-4, 1] and collapse into [-8, 1], while [3, 5] has no overlap and remains separate.
Constraints
1 <= len(intervals) <= 10^5- Each element of
intervalsis a two-integer list[start, end]with-10^9 <= start <= end <= 10^9.
Step-by-step walkthrough
Understand the problem and the overlap rule
We receive an unsorted list of closed intervals
[start, end]withstart <= end, where each interval coversstart,end, and every real number on the continuous number line between them. We need to collapse every chain of intersecting intervals into a single[smallest_start, largest_end]range and return the resulting disjoint ranges sorted bystart.Pay close attention to three boundary behaviors on the real line:
1. Touching endpoints OVERLAP (they share point 6): [2, 6]: 2===========6 [6, 9]: 6========9 merged: 2====================9 -> [2, 9] 2. Consecutive integers DO NOT overlap (real points like 5.5 are uncovered): [0, 5]: 0=============5 [6, 8]: 6=====8 merged: 0=============5 6=====8 -> [[0, 5], [6, 8]] 3. Overlap chains merge transitively ([3, 7] bridges [1, 4] and [6, 10]): [1, 4]: 1=======4 [3, 7]: 3==========7 [6, 10]: 6==========10 merged: 1=======================10 -> [1, 10]Why checking every pair is too slow
A naive brute-force approach treats intervals as vertices in a graph, compares every pair of intervals to test whether they share a point (
max(a, c) <= min(b, d)), and collapses each connected group into[min_start, max_end].With
nup to100,000, testing alln * (n - 1) / 2pairs performs roughly5 * 10^9comparisons (O(n^2)time), which exceeds the time limit. The only reason all-pairs checks were needed is that intersecting intervals sit scattered throughout the input.Key idea: sort by start, then sweep left to right
If we first sort the intervals in ascending order of
start(breaking ties byend), every connected chain of overlapping intervals becomes a contiguous block in the sorted list. We can then sweep from left to right while maintaining one active group[group_start, group_end]at the tail of our output listmerged:Case A: start <= group_end (overlap or shared endpoint) current_group: group_start================group_end next (extends): start===========end -> group_end becomes end next (nested): start===end -> group_end stays group_end! Case B: start > group_end (strict gap) current_group: group_start======group_end next interval: start====end all later ones: start2=====... (also >= start > group_end)Why is
current_grouppermanently sealed in Case B? Because the list is sorted bystart: every later interval starts at or afterstart, which already lies strictly right ofgroup_end. Nothing later can reach back across that uncovered gap, so we closecurrent_groupand open[start, end]as the new active group.Two details prevent classic bugs: - Use
<=, not<: Whenstart == group_end, both closed intervals contain that boundary point (like8in[6, 8]and[8, 11]), so they must merge. - Only growgroup_end, never shrink it: When[4, 6]follows[2, 8],end(6) is smaller thangroup_end(8), so we preservemax(group_end, end).Implement the sort-and-sweep pass
Calling
sorted(intervals)creates a new outer list inO(n log n)time without reordering the caller's input list. Likewise, whenever we open a group inmerged, we allocate a fresh two-element list[start, end]rather than appending the caller's sublist reference—otherwisecurrent_group[1] = endwould mutate one of the caller's inner lists!def merge_intervals(intervals: list[list[int]]) -> list[list[int]]: if not intervals: return [] # Phase 1: Sort intervals by [start, end] ascending; sorted() returns a new list # so the caller's outer list order is never mutated. ordered = sorted(intervals) # merged: list of disjoint [group_start, group_end] pairs ordered by group_start. # Copy the earliest interval into a fresh two-item list to avoid mutating input lists. first_start, first_end = ordered[0] merged: list[list[int]] = [[first_start, first_end]] # Phase 2: Sweep left to right, extending or sealing the active group at merged[-1]. for start, end in ordered[1:]: current_group = merged[-1] group_end = current_group[1] # Closed intervals include both endpoints, so start == group_end shares that single # point and must merge (hence <= rather than <). if start <= group_end: # Take max(group_end, end) so a nested interval like [2, 3] inside [1, 10] # never shrinks the active group's right boundary. if end > group_end: current_group[1] = end else: # Because ordered is sorted by start, every later interval also starts > group_end, # so current_group can never overlap anything else; start a new group. merged.append([start, end]) return mergedTrace Example 1 and Example 2 step by step
Let's trace both examples to verify nested intervals, uncovered real gaps, and shared single-point boundaries:
Example 1: intervals = [[10, 14], [2, 8], [4, 6], [12, 18]] Sorted: ordered = [[2, 8], [4, 6], [10, 14], [12, 18]] Seed with ordered[0]: merged = [[2, 8]] Next [4, 6]: start 4 <= group_end 8 -> nested (6 <= 8) -> merged = [[2, 8]] Next [10, 14]: start 10 > group_end 8 -> gap! New group -> merged = [[2, 8], [10, 14]] Next [12, 18]: start 12 <= group_end 14 -> extend end to 18 -> merged = [[2, 8], [10, 18]] Return [[2, 8], [10, 18]] Example 2: intervals = [[6, 8], [0, 5], [8, 8], [8, 11]] Sorted: ordered = [[0, 5], [6, 8], [8, 8], [8, 11]] Seed with ordered[0]: merged = [[0, 5]] Next [6, 8]: start 6 > group_end 5 -> gap (5.5 uncovered) -> merged = [[0, 5], [6, 8]] Next [8, 8]: start 8 <= group_end 8 -> shares point 8 -> merged = [[0, 5], [6, 8]] Next [8, 11]: start 8 <= group_end 8 -> shares 8, end -> 11 -> merged = [[0, 5], [6, 11]] Return [[0, 5], [6, 11]]Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def merge_intervals(intervals: list[list[int]]) -> list[list[int]]: if not intervals: return [] # Phase 1: Sort intervals by [start, end] ascending; sorted() returns a new list # so the caller's outer list order is never mutated. ordered = sorted(intervals) # merged: list of disjoint [group_start, group_end] pairs ordered by group_start. # Copy the earliest interval into a fresh two-item list to avoid mutating input lists. first_start, first_end = ordered[0] merged: list[list[int]] = [[first_start, first_end]] # Phase 2: Sweep left to right, extending or sealing the active group at merged[-1]. for start, end in ordered[1:]: current_group = merged[-1] group_end = current_group[1] # Closed intervals include both endpoints, so start == group_end shares that single # point and must merge (hence <= rather than <). if start <= group_end: # Take max(group_end, end) so a nested interval like [2, 3] inside [1, 10] # never shrinks the active group's right boundary. if end > group_end: current_group[1] = end else: # Because ordered is sorted by start, every later interval also starts > group_end, # so current_group can never overlap anything else; start a new group. merged.append([start, end]) return merged✅ Submit now — all tests should pass.
Intuition & how it works
Imagine laying strips of masking tape along a wooden ruler to mark covered segments, where each strip [start, end] is a closed interval (a continuous range that includes both endpoint numbers and every real number between them). When the strips sit in a random pile, telling which ones link up into longer chains is awkward. If you first line up all the strips by their left edge from smallest to largest, the job becomes straightforward: pick up the leftmost strip as your active segment, and inspect each remaining strip in order. Whenever the next strip's left edge touches or lands inside your active segment (start <= group_end), glue them together and extend your right edge if the new strip reaches further right; whenever bare ruler separates them (start > group_end), no later strip can bridge back across that gap because every remaining strip starts even further to the right. Sorting geometric intervals by coordinate and scanning them in one pass is called a sweep-line algorithm.
Why does the naive approach fall short? Without sorting first, deciding which intervals belong together requires comparing every pair of intervals (or building a graph and finding connected components, meaning clusters of intervals linked directly or indirectly through chains of overlaps). With up to n = 100,000 intervals, testing all n * (n - 1) / 2 pairs takes roughly 5 billion checks (O(n^2) time), whereas sorting once brings every overlapping neighbor next to the active group in O(n log n) time.
Here is how the sweep works on Example 1 (intervals = [[10, 14], [2, 8], [4, 6], [12, 18]]):
Sorted by start: [[2, 8], [4, 6], [10, 14], [12, 18]]
1. Start with [2, 8] -> merged = [[2, 8]]
2. Read [4, 6]: 4 <= 8 -> nested inside [2, 8], max(8, 6) stays 8 -> merged = [[2, 8]]
3. Read [10, 14]: 10 > 8 -> gap after 8, open new group [10, 14] -> merged = [[2, 8], [10, 14]]
4. Read [12, 18]: 12 <= 14 -> overlaps [10, 14], extend end to 18 -> merged = [[2, 8], [10, 18]]
The returned ranges are disjoint (no two intervals share any point) and already ordered by start.
Complexity
- Time:
O(n log n), wherenislen(intervals). Sorting thentwo-element lists with Python's Timsort takesO(n log n)comparisons, and the single left-to-right sweep afterward inspects each interval once withO(1)constant-time comparisons and appends. - Space:
O(n).sorted(intervals)allocates a list ofnreferences so we do not reorder the caller's input, andmergedholds up tontwo-element lists when all intervals are disjoint.
Edge cases
- Single interval (
[[7, 7]]): Seeded intomergedas a fresh copy and returned unchanged becauseordered[1:]is empty. - Touching endpoints (
[2, 6]and[6, 9], or[6, 8],[8, 8], and[8, 11]): Closed intervals include both endpoints, so sharing a single boundary point satisfiesstart <= group_endand merges them. - Consecutive integers (
[0, 5]and[6, 8]): Because intervals cover continuous real points,5.5is uncovered;6 > 5keeps[0, 5]and[6, 8]separate. - Transitive overlap chains (
[1, 4],[3, 7],[6, 10]): After sorting,[1, 4]and[3, 7]merge into[1, 7], whose updatedgroup_end = 7then absorbs[6, 10]into[1, 10]. - Nested intervals (
[4, 6]inside[2, 8]): Updatingcurrent_group[1]only whenend > group_endprevents[4, 6]from shrinking[2, 8]down to[2, 6]. - Duplicates and point intervals (
[0, 0]repeated): Sorting places identical ranges side by side, and0 <= 0collapses all copies into one[0, 0]. - Extreme negative and positive coordinates (
-10^9to10^9): The sweep only compares endpoints without adding or multiplying them, avoiding integer overflow even in fixed-width 32-bit languages.
Common mistakes
- Writing
start < group_endinstead ofstart <= group_end: Treats endpoints as open and wrongly leaves touching closed ranges like[6, 8]and[8, 11]unmerged. - Writing
start <= group_end + 1: Coalesces consecutive integers like[0, 5]and[6, 8]into[0, 8], ignoring uncovered real numbers in(5, 6)and failing Example 2. - Unconditionally assigning
current_group[1] = end: On[[2, 10], [3, 4], [6, 8]], overwriting10with4makes[6, 8]appear disconnected from[2, 10]. Always keepmax(group_end, end). - Comparing against the previous input element
ordered[i - 1]instead ofmerged[-1]: On[[2, 10], [3, 4], [6, 8]],[6, 8]does not intersect[3, 4], yet it still falls inside[2, 10]. - Appending the original inner list
ordered[0]directly intomerged: Mutatingmerged[-1][1] = endwould alter the caller's input sublist in place; copying[first_start, first_end]avoids side effects.
Alternative approaches
- Endpoint event sweep: Convert each
[start, end]into two events(start, OPEN)and(end, CLOSE), sort events by coordinate withOPENordered beforeCLOSEat ties (so touching endpoints stay active before closing), and maintain anactive_countcounter. A merged range opens whenactive_countrises from0to1and closes when it drops back to0. This also runs inO(n log n)time and generalizes directly when computing peak overlap depth. - Graph connected components: Build an intersection graph over all interval pairs and traverse each component to compute
[min_start, max_end]. Correct, butO(n^2)time and memory cannot handlen = 10^5.
Follow-up questions
- How would you insert a single new interval into an already sorted, disjoint list? Because the existing list is already sorted and disjoint, you can skip sorting altogether and finish in
O(n)time with one pass: copy all intervals withend < new_start, merge every interval satisfyingstart <= new_endinto[min(start, new_start), max(end, new_end)], append that merged interval, and copy the remaining intervals. You can find the first and last overlapping indices inO(log n)using binary search, though building the updated Python list still takesO(n)time due to shifting elements. - What if intervals arrive in a live stream and you must query the merged list at any time? Store the disjoint intervals ordered by
startinside a balanced binary search tree (a sorted tree structure that supports search, insertion, and deletion inO(log k)time forkstored intervals, such asstd::mapin C++ orSortedDictin Python). When[new_start, new_end]arrives, look up the predecessor and successor intervals that satisfystart <= new_endandend >= new_start, delete them from the tree, and insert their combined[min_start, max_end]interval; since every inserted interval can be deleted at most once,mstream arrivals takeO(m log m)total time. - How do the rules change for half-open intervals [start, end)? A half-open interval
[start, end)includesstartand every real point strictly belowend, excludingenditself, so[2, 6)and[6, 9)share zero points. However, in calendar and busy-time coalescing you usually still want back-to-back[2, 6)and[6, 9)merged into one continuous[2, 9)block (keepingstart <= group_end), whereas if you only merge intervals that share positive overlap length you change the check tostart < group_end—confirming which rule the caller wants is an essential clarifying question.
Follow-up questions
- How would you insert a single new interval into an already sorted, disjoint list?
- What if intervals arrive in a live stream and you must query the merged list at any time?
- How do the rules change for half-open intervals [start, end)?
Similar questions
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One
- Increment Digit Array