Consolidate Overlapping Closed Intervals
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Given a collection of closed intervals intervals, where each element intervals[i] = [start_i, end_i] spans every value from start_i through end_i inclusive, consolidate all overlapping ranges and return the resulting disjoint intervals sorted by ascending start.
Two closed intervals [a, b] and [c, d] ordered with a <= c overlap whenever c <= b:
- Ranges that touch at a single boundary coordinate (such as
[0, 6]and[6, 11]) share that coordinate and combine into[0, 11]. - Ranges separated by a positive gap (such as
[3, 6]and[7, 9]) share no common value and remain distinct entries in the output.
Implement merge_intervals(intervals) without assuming any particular ordering of the input list.
Examples
Example 1
Input: intervals = [[12, 16], [2, 5], [4, 9], [20, 25], [5, 7]]
Output: [[2, 9], [12, 16], [20, 25]]
Walk-through: Sorting by start point orders the ranges as [2, 5], [4, 9], [5, 7], [12, 16], [20, 25]. First [2, 5] and [4, 9] combine into [2, 9], which then absorbs [5, 7]. Neither [12, 16] nor [20, 25] intersects any other range, so three disjoint intervals are returned.
Example 2
Input: intervals = [[0, 6], [6, 11]]
Output: [[0, 11]]
Walk-through: Because intervals are closed on both ends, the point 6 belongs to both [0, 6] and [6, 11], fusing them into [0, 11].
Example 3
Input: intervals = [[7, 9], [3, 6]]
Output: [[3, 6], [7, 9]]
Walk-through: No number satisfies both x <= 6 and x >= 7. Sorting places [3, 6] ahead of [7, 9] while keeping both intervals separate.
Constraints
0 <= len(intervals) <= 100_000len(intervals[i]) == 2for everyi-10^9 <= start_i <= end_i <= 10^9- Input elements can appear in any order, including duplicates and zero-length point intervals (
start_i == end_i).
Step-by-step walkthrough
Understand the overlap rule on a number line
We receive up to
100,000closed intervals[start, end]in arbitrary order. Because a closed interval includes both endpoints,[0, 6]contains0,6, and every value between them. Our job is to fuse all intersecting ranges and return a sorted list of disjoint intervals (ranges that share zero points).Sketching the four geometric situations on a number line pins down the exact merge rule:
Number line: 0 1 2 3 4 5 6 7 8 9 10 11 |---|---|---|---|---|---|---|---|---|---|---| Case A (partial overlap): [2, 5] [===========] [4, 9] [===================] Merged -> [===========================] -> [2, 9] Case B (shared endpoint): [0, 6] [=======================] [6, 11] [===================] Merged -> [===========================================] -> [0, 11] (6 is in both!) Case C (fully nested): [2, 9] [===========================] [5, 7] [=======] Merged -> [===========================] -> [2, 9] Case D (unit gap, no shared point): [3, 6] [===========] [7, 9] [=======] Merged -> [===========] [=======] -> [[3, 6], [7, 9]]Whenever two closed ranges
[a, b]and[c, d]are ordered soa <= c, they share at least one coordinate if and only ifc <= b.Why brute-force pairwise merging is too slow
A straightforward trial method scans all pairs in the list, replaces any overlapping pair
[a, b]and[c, d](a <= dandc <= b) with[min(a, c), max(b, d)], and repeats passes until a full scan finds zero overlaps.Although mathematically sound, each scan inspects up to O(n^2) pairs, and a long chain of merges can force up to
nscans for O(n^3) worst-case work. Atn = 100,000, even one O(n^2) scan performs roughly5 * 10^9checks and exceeds any reasonable time budget.That quadratic search is only needed because unsorted ranges can sit anywhere in the input array.
Key insight: sort by start point first
Sorting the intervals in ascending
startorder brings every merge candidate directly behind the active consolidated range.As we build
mergedfrom left to right, each incoming interval[curr_start, curr_end]only needs to be tested against the most recent output rangemerged[-1]:- Every earlier range in
mergedended strictly beforemerged[-1][0](otherwise it would have fused withmerged[-1]). - Sorting guarantees
curr_start >= merged[-1][0]. - Combining those inequalities shows
curr_startlies strictly beyond every earlier range inmerged, so it can never reach back tomerged[-2]or earlier.
Notice why we compare against
merged[-1]rather than the previous input element:Sorted input: [1, 12], [3, 4], [7, 9] 1. Read [1, 12] -> merged = [[1, 12]] 2. Read [3, 4] -> 3 <= 12, so [3, 4] is absorbed -> merged = [[1, 12]] 3. Read [7, 9] -> compare against merged[-1] = [1, 12] (NOT [3, 4]!): 7 <= 12, so [7, 9] is absorbed -> merged = [[1, 12]]Calling
sorted(intervals)in Python builds a new list ordered bystart(andendon ties) without reordering the caller's list:if not intervals: return [] # Phase 1: Sort intervals by [start, end] ascending without mutating the caller's list. sorted_intervals = sorted(intervals) # merged: list of disjoint [start, end] ranges sorted by start, e.g. [[2, 9], [12, 16]]. merged: List[List[int]] = []- Every earlier range in
Sweep left to right and avoid three classic bugs
For each
intervalinsorted_intervals, we comparecurr_startwithlast_end = merged[-1][1]:- Use
<=, not<: Whencurr_start == last_end(as in[0, 6]and[6, 11]), both closed ranges contain that shared endpoint and must fuse. - Extend the end with
max(last_end, curr_end): When a shorter interval sits completely inside the active range (such as[5, 7]inside[2, 9]), assigninglast_merged[1] = curr_enddirectly would shrink[2, 9]down to[2, 7]. Takingmaxkeeps9. - Append a fresh
[curr_start, curr_end]list: Appendingintervaldirectly (merged.append(interval)) would alias the caller's inner list, causing later edits tolast_merged[1]to mutate the caller's input data.
# Phase 2: Sweep left to right, comparing each interval only against the last merged range. for interval in sorted_intervals: curr_start = interval[0] curr_end = interval[1] if not merged: # Copy into a fresh [start, end] list so later updates never mutate the caller's input. merged.append([curr_start, curr_end]) continue last_merged = merged[-1] last_end = last_merged[1] # Use <= (not <) because closed intervals sharing one endpoint (e.g. [0, 6] and [6, 11]) overlap. if curr_start <= last_end: # Take max() so a nested interval like [5, 7] inside [2, 9] never shrinks last_end. last_merged[1] = max(last_end, curr_end) else: # curr_start > last_end means a gap exists, so open a new disjoint interval. merged.append([curr_start, curr_end])Because each new entry in
mergedbegins atcurr_startand we scan in non-decreasingstartorder,mergedis already sorted bystartwhen the sweep finishes.- Use
Trace the examples
Let's walk through Example 1:
intervals = [[12, 16], [2, 5], [4, 9], [20, 25], [5, 7]].Phase 1 (sort): sorted_intervals = [[2, 5], [4, 9], [5, 7], [12, 16], [20, 25]] Phase 2 (sweep): Step Current merged[-1] Test (curr_start <= last_end?) Action merged after ---- --------- ---------- ------------------------------ ---------------------- ---------------------------- 1 [2, 5] (empty) - open [2, 5] [[2, 5]] 2 [4, 9] [2, 5] 4 <= 5 -> True (overlap) end = max(5, 9) = 9 [[2, 9]] 3 [5, 7] [2, 9] 5 <= 9 -> True (nested) end = max(9, 7) = 9 [[2, 9]] 4 [12, 16] [2, 9] 12 <= 9 -> False (gap) open [12, 16] [[2, 9], [12, 16]] 5 [20, 25] [12, 16] 20 <= 16 -> False (gap) open [20, 25] [[2, 9], [12, 16], [20, 25]]Checking Examples 2 and 3:
- Example 2 (
[[0, 6], [6, 11]]):curr_start <= last_endevaluates6 <= 6(True), combining into[[0, 11]]. - Example 3 (
[[7, 9], [3, 6]]): sorting yields[[3, 6], [7, 9]], and7 <= 6isFalse, keeping[[3, 6], [7, 9]].
- Example 2 (
Full solution
Putting both phases together gives the complete implementation:
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 without mutating the caller's list. sorted_intervals = sorted(intervals) # merged: list of disjoint [start, end] ranges sorted by start, e.g. [[2, 9], [12, 16]]. merged: List[List[int]] = [] # Phase 2: Sweep left to right, comparing each interval only against the last merged range. for interval in sorted_intervals: curr_start = interval[0] curr_end = interval[1] if not merged: # Copy into a fresh [start, end] list so later updates never mutate the caller's input. merged.append([curr_start, curr_end]) continue last_merged = merged[-1] last_end = last_merged[1] # Use <= (not <) because closed intervals sharing one endpoint (e.g. [0, 6] and [6, 11]) overlap. if curr_start <= last_end: # Take max() so a nested interval like [5, 7] inside [2, 9] never shrinks last_end. last_merged[1] = max(last_end, curr_end) else: # curr_start > last_end means a gap exists, so open a new disjoint interval. merged.append([curr_start, curr_end]) return merged✅ Submit now — all tests should pass.
Intuition & how it works
Imagine consolidating busy blocks on a daily calendar when teammates hand you sticky notes of reservation windows in random order. Each reservation is a closed interval (a range [start, end] that includes both boundary endpoints), and our goal is to produce disjoint intervals (ranges that are completely separate and share zero points). Once you line those notes up in ascending order of start time, you only ever need to watch the single busy block currently in progress: if the next window begins at or before the current block ends, you stretch the current block's end time when needed; if it begins strictly later, a genuine gap has opened, so you set the finished block aside and start a new one.
Without sorting first, overlapping windows can sit at opposite ends of the array. A naive method has to test every pair of intervals (O(n^2) checks per pass) and repeat passes whenever a newly widened block touches another interval (up to O(n^3) work overall). With n = 100,000 intervals, billions of pairwise checks are far too slow, whereas sorting once places every possible overlap right behind the active block.
Here is how sorting and sweeping processes [[12, 16], [2, 5], [4, 9], [20, 25], [5, 7]]:
- Sort by start coordinate:
[[2, 5], [4, 9], [5, 7], [12, 16], [20, 25]]. - Open with
[2, 5]as the active block:merged = [[2, 5]]. - Inspect
[4, 9]:4 <= 5(overlaps), so update the active end tomax(5, 9) = 9, givingmerged = [[2, 9]]. - Inspect
[5, 7]:5 <= 9(nested), andmax(9, 7) = 9keepsmerged = [[2, 9]]. - Inspect
[12, 16](12 > 9) and[20, 25](20 > 16): both start after a gap, finishing with[[2, 9], [12, 16], [20, 25]].
Complexity
- Time: O(n log n) for
nintervals. Sorting thenintervals by start coordinate takes O(n log n) comparisons, and the single left-to-right pass afterward inspects each interval once with O(1) comparisons and list appends per step. - Space: O(n).
sorted(intervals)allocates ann-element sorted list (keeping the caller's input order intact), andmergedholds up tonoutput ranges when none overlap.
Edge cases
- Empty or single-interval input:
[]returns[]immediately, and[[4, 8]]returns a fresh[[4, 8]]without needing any merge comparisons. - Shared single endpoint:
[0, 6]and[6, 11]both contain6, so6 <= 6fuses them into[0, 11]. - Neighboring integers with no shared value:
[3, 6]and[7, 9]share zero numbers (7 <= 6is false), so they stay separate as[[3, 6], [7, 9]]. - Fully nested intervals:
[2, 9]followed by[5, 7]stays[2, 9]becausemax(9, 7)preserves the larger right endpoint. - Duplicates and tied start points:
[[4, 6], [4, 6]]collapses into[[4, 6]], and equal starts like[[1, 3], [1, 8], [1, 5]]consolidate into[[1, 8]]. - Zero-length point intervals: Single-point ranges such as
[5, 5]obey the exact samecurr_start <= last_endtest ([5, 5]merges with[4, 6]or another[5, 5], and stays separate from[3, 3]). - Extreme negative and positive coordinates (
-10^9to10^9): Endpoints are only compared with<=andmax, never added or subtracted, avoiding integer overflow in fixed-width languages.
Common mistakes
- Writing
<instead of<=in the overlap test: Usingcurr_start < last_endmisses intervals that meet at one boundary point, leaving[[0, 6], [6, 11]]split instead of combining into[[0, 11]]. - Writing
curr_start <= last_end + 1: That fuses discrete integer neighbors like[3, 6]and[7, 9], violating closed-interval semantics. - Assigning
last_merged[1] = curr_endwithoutmax: When a shorter range[5, 7]sits inside[2, 9], omittingmaxaccidentally truncates the active range down to[2, 7]. - Comparing against the previous input element instead of
merged[-1]: After[1, 12]and[3, 4], the next range[7, 9]does not touch[3, 4], yet it still lies inside the consolidated range[1, 12]. - Appending the caller's inner list directly (
merged.append(interval)): Later updatingmerged[-1][1]then silently overwrites the caller's input list.
Alternative approaches
- Coordinate sweep-line (boundary events): Turn each
[start, end]into a+1open event atstartand a-1close event atend, sort events so opens precede closes at tied coordinates (ensuring touching endpoints fuse), and emit a range whenever the active count rises above0and returns to0. This also takes O(n log n) time and O(n) space, though it sorts2nevent tuples instead ofnintervals.
Follow-up questions
- Suppose ranges arrive one by one in a live stream and callers query the consolidated set at any moment; what data structure would you maintain? Keep the active disjoint intervals ordered by
startin a balanced binary search tree (a tree structure that maintains sorted order while supporting search, insertion, and deletion in O(log n) time; in Python,sortedcontainers.SortedListoffers equivalent operations). When[s, e]arrives, binary search for the last stored range withstart <= s(which intersects ifend >= s) and walk forward across stored ranges whilestart <= e; remove every intersecting range found and insert a single[min_start, max_end]replacement. Although one arrival absorbingkstored intervals takes O((k + 1) log n) work, each interval is inserted once and deleted at most once, yielding O(log n) amortized time (average cost per arrival across the entire stream). - What changes if each pair denotes a set of integers so neighboring blocks like [2, 5] and [6, 9] also fuse into [2, 9]? Replace the overlap check
curr_start <= last_endwithcurr_start <= last_end + 1, since no integer exists strictly between5and6. Sorting bystartand updating the right boundary viamax(last_end, curr_end)stay unchanged. In fixed-width integer languages such as C++ or Java, writecurr_start - 1 <= last_end(after guarding againstcurr_start == INT_MIN) solast_end + 1cannot overflow near the maximum integer bound. - How can you consolidate the array in place using O(1) extra memory beyond the sorting step? Perform the consolidation in-place (reusing the input list's slots rather than building a separate output array): sort
intervalsdirectly, maintain a write cursorwrite_idx = 0marking the active merged range insideintervals, and for each indexifrom1upward either updateintervals[write_idx][1] = max(intervals[write_idx][1], intervals[i][1])on overlap or incrementwrite_idx += 1and copyintervals[i]intointervals[write_idx], finally truncatingdel intervals[write_idx + 1:]. The sweep uses O(1) scalar variables, though you should note in an interview that Python's Timsort uses up to O(n) scratch memory whereas heapsort achieves strict O(1) auxiliary space in O(n log n) time, and mutating the caller's array must be explicit in the function contract.
Follow-up questions
- Suppose ranges arrive one by one in a live stream and callers query the consolidated set at any moment; what data structure would you maintain?
- What changes if each pair denotes a set of integers so neighboring blocks like [2, 5] and [6, 9] also fuse into [2, 9]?
- How can you consolidate the array in place using O(1) extra memory beyond the sorting step?
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