Consolidate Overlapping Intervals
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
You are given an array intervals where each entry [start, end] denotes a closed numeric range covering every real number x with start <= x <= end.
Implement a function that combines all ranges that share one or more points into consolidated ranges, returning a list of mutually disjoint [start, end] pairs sorted by start in ascending order.
def merge_intervals(intervals: List[List[int]]) -> List[List[int]]:
Two ranges [a, b] and [c, d] must be combined whenever their intersection is non-empty—including when one range's right endpoint equals the other's left endpoint (b == c) or when one range lies completely inside the other. Ranges arrive in arbitrary order, and an empty input list should produce [].
Examples
Example 1
- Input:
intervals = [[12, 16], [2, 5], [4, 9], [20, 25], [5, 7]] - Output:
[[2, 9], [12, 16], [20, 25]] - Explanation: Ordering by start gives
[2, 5],[4, 9],[5, 7],[12, 16],[20, 25]. Ranges[2, 5]and[4, 9]overlap on[4, 5]to form[2, 9], which also absorbs the nested range[5, 7]. Neither[12, 16]nor[20, 25]intersects any other range.
Example 2
- Input:
intervals = [[6, 11], [0, 6], [14, 19]] - Output:
[[0, 11], [14, 19]] - Explanation:
[0, 6]and[6, 11]meet at coordinate6, so they fuse into a single continuous range[0, 11], while[14, 19]stays separate.
Constraints
0 <= len(intervals) <= 10^4- Each element of
intervalsis a two-integer list[start, end]. 0 <= start < end <= 10^6
Step-by-step walkthrough
Understand the timeline and boundary rules
Each
[start, end]pair is a closed interval — a continuous stretch of numbers fromstartthroughend, including both endpoints. We want to combine any intervals that share at least one point into a single wider interval so the output covers the exact same points with no overlaps left.Visualizing the four ways two intervals can relate on a number line makes every boundary rule clear:
1. Partial overlap: [2----5] and [4-------9] --> merge into [2----------9] 2. Shared boundary: [0-------6] and [6--11] --> merge into [0----------11] (touch at 6) 3. Nested (contained): [2-------------------9] and [5---7] --> merge into [2-------------------9] 4. Separate (gap): [2--3] and [4--5] --> stay [2, 3], [4, 5] (gap between 3 and 4)Notice the difference between cases 2 and 4:
[0, 6]and[6, 11]share the point6, whereas[2, 3]and[4, 5]leave the open stretch between3and4uncovered, so they must remain two separate intervals.Why comparing unsorted pairs is too slow
When intervals arrive in arbitrary order, two intervals that belong to the same merged block can sit at opposite ends of the input list — or even need a third interval at the end of the list to bridge them together (such as
[2, 5],[8, 11], and finally[4, 9]).A naive approach repeatedly scans all pairs
(i, j), merges the first overlapping pair it finds, and restarts from the beginning until no pair overlaps. Each merge inspects up toO(n^2)pairs, and up ton - 1merges can happen, costingO(n^3)time in the worst case. Withn = 10,000intervals, that is far too slow.Key idea: sort by start time so merges become adjacent
If we first sort the intervals by
startcoordinate from smallest to largest, every group of intervals that merges together becomes one contiguous run in the sorted list.Why can we focus only on the very last interval in our
mergedoutput list? Suppose our last merged interval is[cur_start, cur_end]and the next sorted interval is[start, end]. Because the list is sorted,start >= cur_startis guaranteed:Case A: start <= cur_end (overlaps or touches) merged[-1]: [cur_start --------- cur_end] next: [start ----------- end] --> They share at least `start`, so update cur_end = max(cur_end, end). Case B: start > cur_end (gap!) merged[-1]: [cur_start ---- cur_end] next: [start ---- end] every future interval: [>= start ...] --> Every later interval starts at or after `start > cur_end`, so NO future interval can ever reach back to `cur_end`! `merged[-1]` is permanently finished, and `[start, end]` starts a new block.Write the single-pass sweep
Python's built-in
sorted(intervals)compares 2-element lists in lexicographical order (dictionary order: comparing index0first, and breaking ties with index1), which sorts bystartascending without needing a custom key function.Two details keep the loop bug-free:
- Copy
[start, end]when starting a new block: writingmerged.append([start, end])allocates a fresh 2-element list, so updatingmerged[-1][1]later never mutates the caller's original input lists. - Keep the larger endpoint with
max(merged[-1][1], end): if[5, 7]comes right after[2, 9],max(9, 7)keeps9instead of shrinking the block to7.
def merge_intervals(intervals: List[List[int]]) -> List[List[int]]: # Guard empty input immediately so we can safely inspect merged[-1] later. if not intervals: return [] # Phase 1: Sort [start, end] pairs lexicographically (by start ascending, then end ascending). sorted_intervals = sorted(intervals) # merged: list of disjoint [start, end] intervals ordered by start time, e.g. [[2, 9], [12, 16]]. merged: List[List[int]] = [] # Phase 2: Sweep left to right, extending the active block or starting a new one. for start, end in sorted_intervals: # Strict `>` means a real gap exists (touching endpoints like [0, 6] and [6, 11] have 6 <= 6, # so they go to the `else` branch and merge). Append a fresh list to avoid mutating input. if not merged or start > merged[-1][1]: merged.append([start, end]) else: # Use max() because a nested interval like [5, 7] inside [2, 9] must not shrink 9 to 7. merged[-1][1] = max(merged[-1][1], end) return merged- Copy
Trace the examples step by step
Let's trace Example 1 (
[[12, 16], [2, 5], [4, 9], [20, 25], [5, 7]]) and Example 2 ([[6, 11], [0, 6], [14, 19]]):Example 1: sorted_intervals = [[2, 5], [4, 9], [5, 7], [12, 16], [20, 25]] read [2, 5] -> merged is empty -> append [2, 5] | merged = [[2, 5]] read [4, 9] -> 4 <= 5 (overlap!) -> max(5, 9) = 9 | merged = [[2, 9]] read [5, 7] -> 5 <= 9 (nested inside!) -> max(9, 7) = 9 | merged = [[2, 9]] read [12, 16] -> 12 > 9 (gap!) -> append [12, 16] | merged = [[2, 9], [12, 16]] read [20, 25] -> 20 > 16 (gap!) -> append [20, 25] | merged = [[2, 9], [12, 16], [20, 25]] Example 2: sorted_intervals = [[0, 6], [6, 11], [14, 19]] read [0, 6] -> merged is empty -> append [0, 6] | merged = [[0, 6]] read [6, 11] -> 6 <= 6 (shared boundary!) -> max(6, 11) = 11 | merged = [[0, 11]] read [14, 19] -> 14 > 11 (gap!) -> append [14, 19] | merged = [[0, 11], [14, 19]]Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def merge_intervals(intervals: List[List[int]]) -> List[List[int]]: # Guard empty input immediately so we can safely inspect merged[-1] later. if not intervals: return [] # Phase 1: Sort [start, end] pairs lexicographically (by start ascending, then end ascending). sorted_intervals = sorted(intervals) # merged: list of disjoint [start, end] intervals ordered by start time, e.g. [[2, 9], [12, 16]]. merged: List[List[int]] = [] # Phase 2: Sweep left to right, extending the active block or starting a new one. for start, end in sorted_intervals: # Strict `>` means a real gap exists (touching endpoints like [0, 6] and [6, 11] have 6 <= 6, # so they go to the `else` branch and merge). Append a fresh list to avoid mutating input. if not merged or start > merged[-1][1]: merged.append([start, end]) else: # Use max() because a nested interval like [5, 7] inside [2, 9] must not shrink 9 to 7. merged[-1][1] = max(merged[-1][1], end) return merged✅ Submit now — all tests should pass.
Intuition & how it works
Imagine consolidating busy blocks on a person's calendar when meeting sticky notes are tossed onto your desk in random order. If you leave them scrambled, you have to compare every note against every other note to see which meetings run together. Instead, if you line the sticky notes up left-to-right by their start times, you can slide one finger across the timeline: whenever the next meeting starts before (or right at the moment) your current busy block ends, you stretch the current block to cover both; whenever there is a gap of free time, you seal the current block and start a fresh one.
Why does the naive approach fall short? Without sorting, two overlapping intervals can sit anywhere in the list, and merging two intervals into a wider one can suddenly make it overlap a third interval you checked earlier. Repeatedly scanning all pairs until nothing merges can take O(n^3) time in the worst case, which is far too slow for 10,000 intervals.
Here each [start, end] is a closed interval (an interval that includes both endpoints start and end, so [0, 6] and [6, 11] touch at 6 and merge). Sorting [start, end] lists in lexicographical order (comparing the first element start, and breaking ties with end) lets a single left-to-right pass finish the job. Let's trace Example 1 ([[12, 16], [2, 5], [4, 9], [20, 25], [5, 7]]):
Step 1 - Sort by start: [[2, 5], [4, 9], [5, 7], [12, 16], [20, 25]]
Step 2 - Sweep left to right:
[2, 5] -> start first block: merged = [[2, 5]]
[4, 9] -> 4 <= 5 (overlaps!), end=max(5,9): merged = [[2, 9]]
[5, 7] -> 5 <= 9 (nested!), end=max(9,7): merged = [[2, 9]]
[12, 16] -> 12 > 9 (gap!), start new block: merged = [[2, 9], [12, 16]]
[20, 25] -> 20 > 16 (gap!), start new block: merged = [[2, 9], [12, 16], [20, 25]]
Complexity
Let n = len(intervals).
- Time:
O(n log n). Sorting thenintervals takesO(n log n)comparisons, and the singleforloop afterward visits each of thenintervals once, doingO(1)boundary checks and list updates per step. - Space:
O(n).sorted(intervals)creates a sorted outer list of lengthn, andmergedstores up tontwo-element lists when no intervals overlap.
Edge cases
- Empty list
[]: Handled right away and returns[]. - Single interval
[[5, 8]]: Appended as a new[5, 8]list and returned unchanged. - Touching boundary
[[0, 6], [6, 11]]: Because6 > 6isFalse(6 <= 6), the shared endpoint6merges them into[[0, 11]]. - Adjacent integers
[[2, 3], [4, 5]]: Because4 > 3, the uncovered open gap(3, 4)keeps them separate as[[2, 3], [4, 5]]. - Nested interval
[[2, 9], [5, 7]]:max(9, 7)preserves9, absorbing[5, 7]into[[2, 9]]without shrinking the end. - Duplicate intervals
[[3, 7], [3, 7]]: Collapse cleanly into[[3, 7]].
Common mistakes
- Using
<instead of<=for overlap (or>=instead of>for a gap): Treatingstart == merged[-1][1]as non-overlapping leaves[0, 6]and[6, 11]separate instead of merging them into[0, 11]. - Assigning
merged[-1][1] = endwithoutmax(...): If[2, 9]is followed by[5, 7], blindly overwriting the end shrinks[2, 9]into[2, 7]. - Comparing against the previous input interval
sorted_intervals[i - 1]instead ofmerged[-1]: On[[1, 12], [2, 4], [6, 8]],[6, 8]does not overlap[2, 4], yet it still lies inside the active merged block[1, 12]. - Mutating the caller's inner lists by appending
intervaldirectly: Writingmerged.append(interval)aliases the caller's[start, end]list, so modifyingmerged[-1][1]silently alters the input data. Appending[start, end]creates an independent 2-element copy. - Sorting by
endcoordinate instead ofstartcoordinate: Sorting byendcan place a wide interval like[1, 12]after[9, 10], breaking the left-to-right invariant unless you scan backward from right to left.
Alternative approaches
- Coordinate event sweep: A sweep-line algorithm turns each
[start, end]into two point events —(start, -1)for opening and(end, +1)for closing (sorting-1before+1at ties so[0, 6]and[6, 11]stay connected) — then sorts all2nevents and tracks how many intervals are currently open. Whenever the active count rises from0to1an interval begins, and whenever it drops back to0an interval ends; this also runs inO(n log n)time. - Coordinate difference array: A difference array stores only the net change in coverage at each integer coordinate (
diff[start] += 1,diff[end] -= 1over unit segments[x, x + 1)), then computes running prefix sums from0tomax_end(<= 10^6) inO(n + max_end)time without comparison sorting. That only helps when coordinates are small non-negative integers andnis very large.
Follow-up questions
- What are the asymptotic runtime and memory costs of this solution, and how can extra memory be reduced if modifying the input list is allowed? Our solution uses
O(n log n)time andO(n)space because it leaves the input untouched and builds a fresh output list. If the caller permits modifyingintervalsin place, you can callintervals.sort(), maintain awriteindex of the last merged slot insideintervals, merge overlapping entries directly intointervals[write], and slice off the tail withdel intervals[write + 1:]. That eliminates the separate output list, reducing auxiliary memory beyond the sort itself toO(1)(note that Python's Timsort — Python's built-in hybrid merge/insertion sort — still uses up toO(n)temporary scratch pointers in the worst case, whereas an in-place heapsort usesO(1)extra space). - Suppose you already have a sorted list of disjoint intervals and want to add one new interval—how would you adapt the approach? Because an already merged list is sorted and mutually disjoint, no sorting is needed and a single
O(n)scan suffices: copy all intervals ending strictly beforenew_start(end < new_start), absorb every overlapping interval (start <= new_end) into[min(new_start, start), max(new_end, end)], append that merged interval, and copy the remaining intervals (start > new_end). You can find the first and last overlapping positions inO(log n)time using binary search (repeatedly halving the sorted search range), though splicing into a flat Python list still shifts up toO(n)elements unless intervals are stored in a balanced search tree. - How does the runtime change when the input intervals arrive pre-ordered by their starting coordinate? Skipping
sorted(intervals)drops the total runtime fromO(n log n)toO(n), since only the single linear merge pass remains. Interestingly, even if you still callsorted(intervals)in Python, Timsort automatically detects pre-sorted runs in a single scan and finishes inO(n)comparisons!
Follow-up questions
- What are the asymptotic runtime and memory costs of this solution, and how can extra memory be reduced if modifying the input list is allowed?
- Suppose you already have a sorted list of disjoint intervals and want to add one new interval—how would you adapt the approach?
- How does the runtime change when the input intervals arrive pre-ordered by their starting coordinate?
Similar questions
- Flip Interior O Components via Disjoint-Set Union
- Single-Room Feasibility and Minimum Concurrent Rooms
- Measure Connected Island Area
- Minimum Conference Rooms Needed
- Optimal Matrix Chain Parenthesization
- Highest Three Scores per Student
More Apple interview questions
- Technical Project Retrospective: Architecture, Design Trade-Offs, and Stakeholder Alignment Medium
- Thread-Safe 300-Second Sliding Hit Counter Medium
- Fixed-Capacity LRU Cache Operation Stream Medium Pro
- Silicon Verification Essentials: SystemVerilog, UVM, Clock Domains, and Caches Hard Pro
- Navigating Work Eligibility, Resume Accuracy, and Multi-Tier Leveling Medium Pro
- Non-Mutating Grid Island Count Medium Pro
- Target-Sum Contiguous Subarray Count Hard Pro
- Bidirectional Chain Length from an Arbitrary Node Medium Pro
- Authenticated Election APIs and Data Model Easy Pro
- Sliding 300-Second Event Counter Medium Pro