Consolidate Overlapping Intervals
Medium · Coding & Algorithms · Applied Scientist · Technical Screen
Problem Statement
You receive a list intervals where each element is a two-integer list [start, end] denoting a closed continuous range [start, end]. Two ranges [a, b] and [c, d] intersect whenever they contain at least one common point—including a shared boundary endpoint (for example, [3, 7] and [7, 11] intersect at 7 and coalesce into [3, 11]).
Implement:
def merge_intervals(intervals: List[List[int]]) -> List[List[int]]:
Combine all intersecting ranges (including chains of ranges and completely nested sub-ranges) and return a new list of pairwise disjoint [start, end] intervals in ascending order of start.
Examples
Example 1
Input: intervals = [[12, 16], [2, 5], [4, 9], [20, 24], [6, 8]]
Output: [[2, 9], [12, 16], [20, 24]]
Sorting by start coordinate gives [[2, 5], [4, 9], [6, 8], [12, 16], [20, 24]]. [2, 5] and [4, 9] overlap on [4, 5] to form [2, 9], which completely absorbs [6, 8]. [12, 16] and [20, 24] share no points with anything else and remain distinct.
Example 2
Input: intervals = [[3, 7], [7, 11]]
Output: [[3, 11]]
Because endpoints are inclusive, [3, 7] and [7, 11] touch at 7 and coalesce into [3, 11].
Constraints
1 <= len(intervals) <= 10,0000 <= start < end <= 10^9intervalsmay be given in arbitrary order.
Step-by-step walkthrough
Understand when two time ranges merge
We receive up to
10,000closed intervals[start, end]with0 <= start < end <= 10^9, possibly in arbitrary order. Two intervals merge whenever they share at least one point—including just an endpoint—and merging chains transitively across multiple intervals:Touching endpoints merge: [3------7] [7----11] --> [3----------11] Integer gap stays separate: [1--2] [3--4] --> [1--2], [3--4] (no shared point) Nested interval absorbed: [2------------9] [6--8] --> [2------------9]Our output must be a new list of merged
[start, end]intervals with no remaining overlaps.Why checking every pair is too slow
If the intervals are in random order,
[1, 4]at the beginning of the list might connect to[7, 9]near the end only because[4, 7]appears somewhere in the middle. Checking all pairs of intervals and grouping connected components (for example with union-find) inspectsn * (n - 1) / 2pairs—roughly50,000,000comparisons whenn = 10,000.That quadratic work only happens because the intervals are scrambled. On an ordered timeline, overlaps can only happen right next to each other.
Key idea: sort by start time so overlaps only touch the last range
Suppose we sort all intervals by their
startcoordinate from smallest to largest. As we scan left to right, we maintainmerged, our list of finished and active ranges. Look at the very last range inmerged,[last_start, last_end], and the next incoming interval[start, end]. Because we sorted by start time, we already knowlast_start <= start. Only two cases are possible:Case 1: start <= last_end (overlap or touch) last_range: [last_start -------- last_end] incoming: [start ----------- end] updated: [last_start ------------------- max(last_end, end)] Case 2: start > last_end (strict gap) last_range: [last_start ---- last_end] incoming: [start ---- end] action: last_range is sealed forever; append [start, end] as the new active range!Why can we seal
last_rangeforever in Case 2? Because every future interval insorted_intervalsstarts at or afterstart, which is already strictly greater thanlast_end—so no later interval can ever reach back across the gap!Sort and sweep through the intervals
In Python, comparing two
[start, end]lists compares index0(start) first and index1(end) on ties, sosorted(intervals)puts everything in ascending start order without mutating the caller's list.During the single left-to-right pass, pay close attention to three details: 1. Copy
[start, end]when appending so extendinglast_range[1]later never mutates the caller's input lists. 2. Use<=instead of<so touching endpoints like[3, 7]and[7, 11]merge. 3. Usemax(last_end, end)so a completely contained interval like[2, 3]inside[1, 5]does not shrinklast_endfrom5down to3.def merge_intervals(intervals: List[List[int]]) -> List[List[int]]: # Two-element lists compare item by item, so sorted() orders by start time # (and by end time on ties) while leaving the caller's list untouched. sorted_intervals = sorted(intervals) # merged: non-overlapping [start, end] ranges in ascending order of start time. merged: List[List[int]] = [] for start, end in sorted_intervals: if not merged: # Copy [start, end] so mutating merged[-1] later never mutates input sublists. merged.append([start, end]) continue last_range = merged[-1] last_end = last_range[1] # Use <= (not <) because closed intervals that share an endpoint (like [3, 7] and [7, 11]) merge. if start <= last_end: # Take max(last_end, end) so a shorter nested range like [2, 3] inside [1, 5] never shrinks last_end. last_range[1] = max(last_end, end) else: # Strict gap (start > last_end): every remaining interval also starts >= start, so last_range is final. merged.append([start, end]) return mergedTrace Example 1 and Example 2
Let us trace Example 1 (
[[12, 16], [2, 5], [4, 9], [20, 24], [6, 8]], which sorts to[[2, 5], [4, 9], [6, 8], [12, 16], [20, 24]]):Incoming last_range Check (start <= last_end?) Action merged ------------------------------------------------------------------------------------------------------------ [2, 5] none first interval append [2, 5] [[2, 5]] [4, 9] [2, 5] 4 <= 5 (True) end = max(5, 9) = 9 [[2, 9]] [6, 8] [2, 9] 6 <= 9 (True, nested!) end = max(9, 8) = 9 [[2, 9]] [12, 16] [2, 9] 12 <= 9 (False, gap!) append [12, 16] [[2, 9], [12, 16]] [20, 24] [12, 16] 20 <= 16 (False, gap!) append [20, 24] [[2, 9], [12, 16], [20, 24]]And Example 2 (
[[3, 7], [7, 11]]): -[3, 7]startsmerged = [[3, 7]]. -[7, 11]checks7 <= 7(True), updatinglast_range[1] = max(7, 11) = 11to produce[[3, 11]].Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def merge_intervals(intervals: List[List[int]]) -> List[List[int]]: # Two-element lists compare item by item, so sorted() orders by start time # (and by end time on ties) while leaving the caller's list untouched. sorted_intervals = sorted(intervals) # merged: non-overlapping [start, end] ranges in ascending order of start time. merged: List[List[int]] = [] for start, end in sorted_intervals: if not merged: # Copy [start, end] so mutating merged[-1] later never mutates input sublists. merged.append([start, end]) continue last_range = merged[-1] last_end = last_range[1] # Use <= (not <) because closed intervals that share an endpoint (like [3, 7] and [7, 11]) merge. if start <= last_end: # Take max(last_end, end) so a shorter nested range like [2, 3] inside [1, 5] never shrinks last_end. last_range[1] = max(last_end, end) else: # Strict gap (start > last_end): every remaining interval also starts >= start, so last_range is final. merged.append([start, end]) return merged✅ Submit now — all tests should pass.
Intuition & how it works
Imagine consolidating busy blocks on a daily calendar from a pile of shuffled meeting sticky notes. If the notes sit in random order on your desk, checking whether two meetings connect (possibly through a third bridge meeting!) forces you to compare notes against everything else. Once you line the notes up from earliest start time to latest start time, you can simply slide your finger down the page: keep extending your current busy block whenever the next meeting starts before (or right as) the current block ends, and start a fresh block only when you hit an open gap.
Each [start, end] here is a closed interval (a range that includes both its start and end endpoints, so [3, 7] and [7, 11] share point 7), and overlap is transitive (if interval A overlaps B and B overlaps C, all three merge into one continuous range). A naive approach tests every pair of intervals and groups connected components, taking O(n^2) time—around 50 million pair checks for 10,000 intervals.
Sorting by start reduces the entire merge to one linear scan because any interval that connects to our current active range [last_start, last_end] must have start <= last_end. Here is how [[12, 16], [2, 5], [4, 9], [6, 8]] works step by step:
1. Sort by start: [[2, 5], [4, 9], [6, 8], [12, 16]].
2. Read [2, 5]: merged is empty, so start merged = [[2, 5]].
3. Read [4, 9]: Since 4 <= 5, it overlaps [2, 5]; extend last_end to max(5, 9) = 9, giving merged = [[2, 9]].
4. Read [6, 8]: Since 6 <= 9, it lies inside [2, 9]; max(9, 8) = 9 leaves merged = [[2, 9]].
5. Read [12, 16]: Since 12 > 9, there is a gap after 9 that no later interval can cross; append [12, 16] to finish with [[2, 9], [12, 16]].
Complexity
Let n be the number of intervals in intervals.
- Time:
O(n log n). Sorting thenintervals by start time takesO(n log n)comparisons, and the single left-to-right merge loop inspects each interval once inO(1)time (O(n)total), so sorting dominates. - Space:
O(n).sorted(intervals)creates ann-element shallow list copy, andmergedstores up tonoutput intervals when no intervals overlap.
Edge cases
- Single interval (
[[5, 7]]): Appended once and returned as[[5, 7]]. - Touching endpoints (
[[3, 7], [7, 11]]): Merged into[[3, 11]]because7 <= 7satisfiesstart <= last_end. - Adjacent integers with no shared point (
[[1, 2], [3, 4]]): Kept separate as[[1, 2], [3, 4]]because3 > 2(unlike discrete integer-set problems,[1, 2]and[3, 4]leave the open gap(2, 3)uncovered). - Completely nested intervals (
[[2, 15], [5, 9]]):max(15, 9)keepslast_end = 15rather than shrinking it to9. - Identical intervals or tied start times (
[[1, 3], [1, 7], [1, 3]]): Merged cleanly into[[1, 7]]. - Large coordinates (
0to10^9): We never allocate an array indexed by timestamp (which would require10^9slots and run out of memory); we only compare endpoint integers directly.
Common mistakes
- Writing
start < last_endinstead ofstart <= last_end: Fails Example 2 ([[3, 7], [7, 11]]) by leaving touching intervals unmerged. - Overwriting
last_range[1] = endinstead ofmax(last_end, end): On[[1, 5], [2, 3], [4, 8]],[2, 3]would shrink the active range to[1, 3], causing[4, 8]to falsely split off as a separate range! - Sorting by
endtime instead ofstarttime: After sorting byend([[2, 3], [4, 5], [1, 6]]),[1, 6]arrives last and overlaps both earlier ranges inmerged, breaking the single-range check. - Appending the original sublist
intervalwithout copying[start, end]: Mutatinglast_range[1]in place then silently corrupts the caller's input list!
Alternative approaches
- Boundary event sweep: A sweep-line algorithm converts each interval into a
+1start event and a-1end event, sorts all2nevents along the timeline (ordering+1before-1at equal coordinates so touching ranges connect), and emits a merged interval whenever the active counter rises from0and drops back to0. It also runs inO(n log n)time and generalizes naturally when you need overlap depth (such as minimum meeting rooms).
Follow-up questions
- What changes in your implementation and runtime if the caller guarantees
intervalsarrives pre-sorted by start coordinate? Simply remove thesorted(intervals)step and run the linear merge loop directly overintervals, dropping the time complexity fromO(n log n)toO(n)and avoiding theO(n)sorted copy. (Interestingly, Python's built-in Timsort—a hybrid sorting algorithm designed to exploit existing order—already detects a pre-sorted run inO(n)comparisons, though skippingsorted()still saves allocating the intermediate list and makes theO(n)guarantee explicit.) - Can you reduce the auxiliary memory usage beyond
O(n)if mutating the input list is allowed? Our solution runs inO(n log n)time andO(n)space. If the caller permits mutatingintervals, we can turn the merge pass into an in-place algorithm (one that reuses the input array instead of allocating a separate output list): callintervals.sort(), maintain awriteindex starting at0, merge overlapping intervals intointervals[write], advancewrite += 1on gaps, and slice off the tail withdel intervals[write + 1:]. That eliminates the separate output allocation, leaving only the sorting algorithm's internal scratch space (O(n)worst-case pointers in Python's Timsort, orO(1)auxiliary space in C++ heapsort). - How should the function behave if malformed ranges with
start > endcan appear in the input? Clarify the expected contract with the interviewer before coding, because running the sweep blindly on[5, 1]treats5as the start and1as the end and corrupts nearby merges. In most APIs and backend services, the safest choice is strict fail-fast validation: run anO(n)check at the top ofmerge_intervalsand raise a descriptiveValueErrorwheneverstart > end(orstart >= endif zero-length intervals are disallowed). If the upstream data source is known to occasionally swap timestamps, normalize each pair to[min(a, b), max(a, b)]before sorting; in an analytics pipeline, filter invalid rows out and increment an error metric.
Follow-up questions
- What changes in your implementation and runtime if the caller guarantees `intervals` arrives pre-sorted by start coordinate?
- Can you reduce the auxiliary memory usage beyond `O(n)` if mutating the input list is allowed?
- How should the function behave if malformed ranges with `start > end` can appear in the input?
Similar questions
- Place One Hub to Minimize Maximum Grid Distance
- Evaluate Large Batches of Variable Ratio Queries
- SQL Daily Active Users and Distinct Palindromic Subsequences
- Single-Domain BFS Web Crawler
- In-Memory Inverted Sentence Index
- Design an O(1) LRU Cache
More Amazon interview questions
- Minimizing Worst-Case Grid Distance with One Extra Hub Medium
- Lowest Inversion Count When Merging Two Strings Hard
- Amazon Final-Round Intern Behavioral Prompts Easy Pro
- Amazon Onsite Leadership Principles Behavioral Loop Medium Pro
- Leadership and Generative AI Behavioral Screen Easy Pro
- Amazon Software Engineering Intern Behavioral Screen Hard Pro
- Core Engineering Ownership and Leadership Prompts Medium Pro
- Data Science Behavioral Scenarios on Amazon Leadership Principles Medium Pro
- Target Sum Pair and Longest Unique Substring Medium Pro
- String Rearrangement, K-Way List Merge, and Random-Pointer Cloning Medium Pro