Merge Overlapping Intervals
Medium · Coding & Algorithms · Software Engineer · Online Assessment
Problem Statement
Given a collection of closed integer intervals intervals, where each element intervals[i] = [start_i, end_i] spans every real number x satisfying start_i <= x <= end_i, combine every group of overlapping intervals into a single interval and return the resulting disjoint intervals ordered by increasing start coordinate.
The input list arrives in arbitrary order and may include duplicate intervals, intervals completely contained inside wider intervals, zero-length point intervals (start_i == end_i), and negative coordinates.
Two closed intervals [a, b] and [c, d] overlap whenever max(a, c) <= min(b, d)—that is, whenever at least one number belongs to both. In particular, intervals that meet at a single shared endpoint (such as [1, 6] and [6, 11], which both include 6) must be combined into [1, 11], whereas intervals separated by an open gap (such as [2, 9] and [10, 14], which leave numbers like 9.5 uncovered) remain separate.
def merge_intervals(intervals: List[List[int]]) -> List[List[int]]:
Examples
Example 1
Input: intervals = [[10, 14], [2, 5], [4, 9], [20, 22]]
Output: [[2, 9], [10, 14], [20, 22]]
Sorting by start yields [2, 5], [4, 9], [10, 14], [20, 22]. [2, 5] and [4, 9] share [4, 5] and combine into [2, 9], while [10, 14] (10 > 9) and [20, 22] (20 > 14) have no overlap with earlier spans.
Example 2
Input: intervals = [[6, 11], [-5, -1], [1, 6], [2, 4]]
Output: [[-5, -1], [1, 11]]
Sorting produces [-5, -1], [1, 6], [2, 4], [6, 11]. [-5, -1] stays isolated; [2, 4] lies completely inside [1, 6], and [6, 11] shares boundary point 6 with [1, 6], extending that span to [1, 11].
Constraints
0 <= len(intervals) <= 10^5len(intervals[i]) == 2-10^9 <= start_i <= end_i <= 10^9- Return
[]whenintervalsis empty, and do not mutate the caller's input lists.
Step-by-step walkthrough
Understand closed intervals and the overlap condition
Every input pair
[start, end]represents a closed interval (all real numbersxsatisfyingstart <= x <= end, inclusive of both endpoints). Two closed intervals[a, b]and[c, d]overlap whenever at least one number belongs to both—equivalently,max(a, c) <= min(b, d):Number line: 1 2 4 5 6 9 10 11 . [=======] . . . . [2, 5] and [4, 9] share [4, 5] -> merge to [2, 9] . . [===========] . . [===========] . . . . [1, 6] and [6, 11] share point 6 -> merge to [1, 11] . . . [===============] . [===============] . . [2, 9] and [10, 14] share nothing -> stay separate . . . . . . [==== (values like 9.5 lie uncovered between 9 and 10!)Pay close attention to the boundary rule:
[1, 6]and[6, 11]share6and merge, whereas[2, 9]and[10, 14]share zero points and stay separate.Why pairwise brute-force merging is too slow
A naive loop searches all pairs
(i, j)in the list, merges the first overlapping pair into[min(a, c), max(b, d)], and repeats from scratch until no pair overlaps:- Scanning for a single overlapping pair can check
O(n^2)pairs. - Each merge removes
1interval, so up ton - 1merges can occur.
In the worst case that costs
O(n^3)operations—far too slow forn = 10^5.- Scanning for a single overlapping pair can check
Key insight: sort by start coordinate first
Why did the naive loop have to re-check distant pairs? Because an early-starting interval could sit anywhere near the end of an unsorted list. Sorting all intervals by
startin ascending order unlocks a single-pass invariant:Active span at merged[-1]: [=========] ^ last_end Case A (start <= last_end): [=======] -> shares 'start', so absorb into merged[-1]! Case B (start > last_end): [=====] -> open gap! Every later span starts >= start > last_end, so merged[-1] can never grow again!Because every remaining interval in sorted order has
future_start >= start, as soon asstart > last_end, no later interval can ever reach back across that gap to touchmerged[-1]. Consequently, each interval only needs to be compared againstmerged[-1].Code the single-pass sweep
After handling
if not intervals: return []and sorting intosorted_intervals, initializemergedwith a fresh copy[first_start, first_end]of the earliest interval and sweep through the rest:- Shared boundary points (
<=, not<): Whenstart == last_end, both closed intervals contain that point, sostart <= last_endmerges them. - Nested intervals (
max(last_end, end)): When[2, 4]lies inside[1, 6], blindly assigningend(4) would shrink[1, 6]to[1, 4]and miss the later[6, 11]merge! Takingmax(last_end, end)preserves6. - Protect caller lists: Always allocate a fresh
[start, end]two-element list instead of appending references to the caller's inner lists.
sorted_intervals = sorted(intervals) first_start, first_end = sorted_intervals[0] merged: List[List[int]] = [[first_start, first_end]] for start, end in sorted_intervals[1:]: last_interval = merged[-1] last_end = last_interval[1] if start <= last_end: last_interval[1] = max(last_end, end) else: merged.append([start, end])- Shared boundary points (
Walk through Example 1 and Example 2 step by step
Example 1:
intervals = [[10, 14], [2, 5], [4, 9], [20, 22]]Sorted: [2, 5], [4, 9], [10, 14], [20, 22] Seed: merged = [[2, 5]] Read [4, 9]: 4 <= 5 (overlap!) -> end = max(5, 9) = 9 -> merged = [[2, 9]] Read [10, 14]: 10 > 9 (gap!) -> start new span -> merged = [[2, 9], [10, 14]] Read [20, 22]: 20 > 14 (gap!) -> start new span -> merged = [[2, 9], [10, 14], [20, 22]]Example 2:
intervals = [[6, 11], [-5, -1], [1, 6], [2, 4]]Sorted: [-5, -1], [1, 6], [2, 4], [6, 11] Seed: merged = [[-5, -1]] Read [1, 6]: 1 > -1 (gap!) -> start new span -> merged = [[-5, -1], [1, 6]] Read [2, 4]: 2 <= 6 (nested!) -> end = max(6, 4) = 6 -> merged = [[-5, -1], [1, 6]] Read [6, 11]: 6 <= 6 (touch!) -> end = max(6, 11)= 11 -> merged = [[-5, -1], [1, 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 point (and by end point on ties). # Built-in sorted() compares [start, end] pairs element-by-element without mutating input. sorted_intervals = sorted(intervals) # merged: list of non-overlapping [start, end] intervals sorted by start; # merged[-1] is the active group currently growing. first_start, first_end = sorted_intervals[0] merged: List[List[int]] = [[first_start, first_end]] # Phase 2: Sweep left to right; once sorted, an interval can only overlap merged[-1]. for start, end in sorted_intervals[1:]: last_interval = merged[-1] last_end = last_interval[1] # Closed intervals include both endpoints, so '<=' merges touching endpoints # like [1, 6] and [6, 11] (which share point 6). if start <= last_end: # Use max() so a nested interval like [2, 3] inside [1, 10] never shrinks last_end. last_interval[1] = max(last_end, end) else: # Because start > last_end and all later intervals start >= start, # last_interval can never merge again. Append a fresh copy to protect caller data. merged.append([start, end]) return merged✅ Submit now — all tests should pass.
Intuition & how it works
Picture tidying up reservation blocks on a shared room schedule when requests arrived out of chronological order. While paper slips sit shuffled in a pile, combining two overlapping bookings can create a wider block that suddenly bridges into another slip buried elsewhere in the stack, forcing repeated passes. Arranging every slip from earliest start time to latest start time reduces the job to one clean left-to-right sweep: the next booking either overlaps the single active block at the tail of your output, or begins strictly past its end—and once an open gap appears, no later booking can ever reach back across that gap.
Without sorting first, comparing only adjacent input items misses overlaps separated by unrelated entries (such as [2, 5] and [4, 9] sitting after [10, 14]). Repeatedly scanning all O(n^2) pairs and fusing one pair per pass works on tiny lists, but up to n - 1 merges drive worst-case runtime to O(n^3), timing out completely near n = 10^5. Sorting once in O(n log n) time makes the merge sweep itself strictly O(n).
Let's trace Example 2, [[6, 11], [-5, -1], [1, 6], [2, 4]]:
- Sort by start:
[[-5, -1], [1, 6], [2, 4], [6, 11]], and seedmerged = [[-5, -1]]. - Visit
[1, 6]: Start1exceeds active end-1, so[-5, -1]is permanently finished and we append[1, 6](merged = [[-5, -1], [1, 6]]). - Visit
[2, 4]: Since2 <= 6, it overlaps[1, 6]; setting the end tomax(6, 4) = 6prevents the nested[2, 4]from shrinking[1, 6]. - Visit
[6, 11]: Because closed intervals contain both endpoints,6 <= 6means point6belongs to both[1, 6]and[6, 11], extending the active end tomax(6, 11) = 11and returning[[-5, -1], [1, 11]].
Complexity
- Time:
O(n log n), wheren = len(intervals). Sortingntwo-element lists with Python's Timsort (a hybrid merge-and-insertion sort) takesO(n log n)comparisons, and the single linear sweep afterward visits each interval once inO(1)time per step. - Space:
O(n).sorted_intervalsholdsnlist references (plus Timsort's scratch buffer of up ton / 2references), andmergedstores up tontwo-element output lists when every interval is disjoint.
Edge cases
- Empty input (
[]): Returns[]immediately before indexingsorted_intervals[0]. - Single or zero-length point interval (
[[5, 5]]): Returns a fresh copy[[5, 5]]without entering the loop. - Shared single-point boundary (
[[1, 6], [6, 11]]): Merges into[[1, 11]]because both closed intervals include6. - Consecutive integers (
[[2, 9], [10, 14]]): Kept separate as[[2, 9], [10, 14]]because real numbers strictly between9and10belong to neither interval. - Nested intervals (
[[1, 6], [2, 4], [6, 11]]):max(last_end, end)retains6across[2, 4]so[6, 11]still merges into[[1, 11]]. - Duplicates and extreme coordinates (
±10^9): Identical spans sort side-by-side and collapse into one, and arbitrary-precision Pythonints avoid overflow.
Common mistakes
- Testing
start < last_endinstead ofstart <= last_end: Fails to merge closed intervals that touch at one boundary point (such as[1, 6]and[6, 11]in Example 2). - Assigning
last_interval[1] = endwithoutmax: Shrinks the active block whenever a shorter interval sits nested inside a wider one, breaking downstream merges. - Testing
start <= last_end + 1: Treats continuous closed intervals like discrete integer ranges;[2, 9]and[10, 14]must remain separate. - Sweeping without sorting first: Only merges overlapping intervals that happen to sit adjacent in the raw input.
- Mutating the caller's inner lists: Appending
sorted_intervals[i]directly and editinglast_interval[1]mutates the caller's input in place.
Alternative approaches
- Coordinate sweep-line algorithm: A sweep-line algorithm (converting interval endpoints into sorted coordinate events processed left to right) emits
(start, -1)and(end, +1)per interval, ordering-1before+1on coordinate ties so touching endpoints fuse before closing. Tracking active coverage depth and recording spans where depth transitions0 -> 1and1 -> 0also runs inO(n log n)time, at the cost of allocating2nevent tuples.
Follow-up questions
- What data structure would you maintain if new intervals arrived dynamically one at a time and callers queried the merged state online? Maintain the disjoint merged intervals inside a balanced binary search tree (a self-balancing ordered tree such as an AVL or red-black tree, or
sortedcontainers.SortedDictin Python) keyed bystart. When[s, e]arrives, look up the predecessor interval with largeststart <= s; if itsend >= s, remove it and sets = pred_start,e = max(e, pred_end). Then repeatedly remove every successor interval whosestart <= e, updatinge = max(e, succ_end), and insert the consolidated[s, e]. Because each inserted interval can be deleted at most once over the entire stream, the amortized time (average cost per operation across any sequence of updates) isO(log n)per insertion. - If mutating the input array is allowed, how can you compact the merged result in place using O(1) extra memory beyond the sort? Use an in-place algorithm (reusing the input list's own slots rather than allocating
merged). Guardif not intervals: return intervals, sortintervals.sort(), and keep a write cursorwrite = 0marking the active merged slot. For eachreadin1 .. len(intervals) - 1, ifintervals[read][0] <= intervals[write][1], setintervals[write][1] = max(intervals[write][1], intervals[read][1]); otherwise advancewrite += 1and setintervals[write] = intervals[read], finishing withdel intervals[write + 1:]inO(1)extra index variables. - How would your sort order and boundary checks change if each endpoint could independently be inclusive (closed) or exclusive (open)? Represent each interval as
(start, start_closed, end, end_closed)and sort by(start, not start_closed)so inclusive starts[p, ...precede exclusive starts(p, ...at tied coordinatep(preventing[1, 3],(3, 10],[3, 4]from prematurely splitting at3). Wheneverstart < last_endthe spans overlap; atstart == last_end, they share pointpifflast_end_closed and start_closed(or form a gapless union ifflast_end_closed or start_closed, such as[1, 3)union[3, 5]). When extending the right boundary, adopt(end, end_closed)ifend > last_end, or setlast_end_closed = last_end_closed or end_closedifend == last_end.
Follow-up questions
- What data structure would you maintain if new intervals arrived dynamically one at a time and callers queried the merged state online?
- If mutating the input array is allowed, how can you compact the merged result in place using O(1) extra memory beyond the sort?
- How would your sort order and boundary checks change if each endpoint could independently be inclusive (closed) or exclusive (open)?
Similar questions
- Choosing Between Promise.all, Promise.any, and Promise.allSettled
- 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