Merge Overlapping Intervals
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
You are given a list intervals where each element [start, end] represents a closed interval on the number line (start <= end). Implement:
def merge_intervals(intervals: List[List[int]]) -> List[List[int]]:
Combine all intervals that overlap or touch into consolidated intervals, and return the resulting disjoint intervals ordered by ascending start coordinate.
Follow these rules:
- Closed-interval overlap: Given two intervals
[a, b]and[c, d]witha <= c, they overlap wheneverc <= b. Sharing a single boundary point (c == b) counts as overlapping and merges into[a, max(b, d)]. - Edge cases: Return
[]ifintervalsis empty. Properly handle single-element inputs, duplicate intervals, zero-length point intervals ([x, x]), and narrower intervals nested completely inside wider ones.
Examples
Example 1
Input: intervals = [[6, 9], [1, 4], [3, 5], [12, 15]]
Output: [[1, 5], [6, 9], [12, 15]]
After ordering by start ([1, 4], [3, 5], [6, 9], [12, 15]), [1, 4] and [3, 5] overlap over [3, 4] and combine into [1, 5]. Neither [6, 9] nor [12, 15] touches any neighbor, so both remain separate.
Example 2
Input: intervals = [[2, 7], [7, 10], [3, 5]]
Output: [[2, 10]]
[3, 5] lies strictly inside [2, 7], and [7, 10] meets [2, 7] at boundary point 7, so all three collapse into [2, 10].
Constraints
0 <= len(intervals) <= 10^40 <= start_i <= end_i <= 10^4
Step-by-step walkthrough
Restate the problem and overlap rule
Given a list of closed intervals
[start, end](each interval includes both endpoints, withstart <= end, given in any order), we want to merge every overlapping or touching group into a single interval and return the resulting non-overlapping intervals sorted bystart:Overlapping: [1, 4] and [3, 5] -> [1, 5] (share [3, 4]) Touching: [2, 7] and [7, 10] -> [2, 10] (share point 7) Separated: [1, 5] and [6, 9] -> [1, 5], [6, 9] (gap between 5 and 6)Whenever
a <= c, two intervals[a, b]and[c, d]overlap if and only ifc <= b. An empty input list[]has zero intervals to merge and returns[].Why pairwise merging without sorting is too slow
A direct brute-force idea is to scan every pair of intervals
(i, j), fuse the first overlapping pair[a, b]and[c, d]into[min(a, c), max(b, d)], and repeat from scratch until a full pass finds zero overlaps.Why does that time out? - Checking all pairs in a list of length
ntakesO(n^2)comparisons. - Up ton - 1merges can happen one at a time, givingO(n^3)worst-case time — hundreds of billions of operations whenn = 10,000.The wasted effort comes from comparing intervals far apart on the number line (like
[1, 4]and[12, 15]) over and over.Key idea: sort by start time so overlaps sit side by side
Once we sort all intervals by
startin ascending order (comparing[start, end]pairs sorts bystartfirst and breaks ties byend), any interval that overlaps our current merged block must appear immediately next in the sorted sequence. Look at the three things that can happen when we compare the next sorted interval[start, end]against our active merged block[last_start, last_end]:Number line: 0 1 2 3 4 5 6 7 8 9 10 11 12 Active block: |--------------| [2, 7] Case A (nested): |-----| [3, 5]: 3 <= 7 -> end stays max(7, 5) = 7 Case B (extends): |--------| [7, 10]: 7 <= 7 -> end grows to max(7, 10) = 10 Case C (gap): |--| [11, 12]: 11 > 10 -> close [2, 10], open [11, 12]Two rules govern the entire left-to-right sweep: 1. Overlap or touch (
start <= last_end): Fuse them by settinglast_end = max(last_end, end). Using<=catches touching endpoints ([2, 7]and[7, 10]), andmax(...)prevents a nested interval like[3, 5]from shrinking[2, 7]down to[2, 5]. 2. Strict gap (start > last_end): Because the list is sorted by start time, every later interval haslater_start >= start > last_end. None of them can ever reach back into[last_start, last_end], so[last_start, last_end]is permanently finished and[start, end]opens a new block.Write the linear sweep cleanly
To keep the code bug-free and friendly to callers: - Guard
if not intervals: return []right up front so we can safely seedmergedwith a copy of the first sorted interval[[first_start, first_end]]. - Usesorted(intervals)and fresh[start, end]lists so updatinglast_merged[1]never mutates the caller's input list behind their back. - Unpacklast_merged = merged[-1]andlast_end = last_merged[1]instead of repeatingmerged[-1][1].from typing import List def merge_intervals(intervals: List[List[int]]) -> List[List[int]]: if not intervals: return [] # Phase 1: Sort a copy by start ascending (ties broken by end ascending) without mutating `intervals`. sorted_intervals = sorted(intervals) # merged: list of non-overlapping [start, end] blocks built in ascending start order. first_start, first_end = sorted_intervals[0] merged: List[List[int]] = [[first_start, first_end]] # Phase 2: Sweep left to right, extending the active block or starting a new one. for start, end in sorted_intervals[1:]: last_merged = merged[-1] last_end = last_merged[1] # Closed intervals touch or overlap whenever start <= last_end (e.g., [2, 7] and [7, 10] share 7). if start <= last_end: # Keep max(last_end, end) so a nested interval like [3, 5] inside [2, 7] never shrinks the block. last_merged[1] = max(last_end, end) else: # Every remaining interval starts >= `start` > `last_end`, so `last_merged` is permanently finished. merged.append([start, end]) return mergedWalk through Example 1 and Example 2
Let's trace Example 1 (
[[6, 9], [1, 4], [3, 5], [12, 15]]), which sorts to[[1, 4], [3, 5], [6, 9], [12, 15]]:Step | Current interval | last_merged | Check (start <= last_end?) | merged after step -----+------------------+-------------+----------------------------+------------------------------- init | [1, 4] | - | seed first block | [[1, 4]] 1 | [3, 5] | [1, 4] | 3 <= 4 -> max(4, 5) = 5 | [[1, 5]] 2 | [6, 9] | [1, 5] | 6 <= 5 is False -> append | [[1, 5], [6, 9]] 3 | [12, 15] | [6, 9] | 12 <= 9 is False -> append | [[1, 5], [6, 9], [12, 15]]In Example 2 (
[[2, 7], [7, 10], [3, 5]]), sorting produces[[2, 7], [3, 5], [7, 10]]andmergedstarts as[[2, 7]]. First[3, 5]has3 <= 7, keepingmax(7, 5) = 7. Next[7, 10]has7 <= 7, extending[2, 7]to[2, max(7, 10)] = [2, 10].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 a copy by start ascending (ties broken by end ascending) without mutating `intervals`. sorted_intervals = sorted(intervals) # merged: list of non-overlapping [start, end] blocks built in ascending start order. first_start, first_end = sorted_intervals[0] merged: List[List[int]] = [[first_start, first_end]] # Phase 2: Sweep left to right, extending the active block or starting a new one. for start, end in sorted_intervals[1:]: last_merged = merged[-1] last_end = last_merged[1] # Closed intervals touch or overlap whenever start <= last_end (e.g., [2, 7] and [7, 10] share 7). if start <= last_end: # Keep max(last_end, end) so a nested interval like [3, 5] inside [2, 7] never shrinks the block. last_merged[1] = max(last_end, end) else: # Every remaining interval starts >= `start` > `last_end`, so `last_merged` is permanently finished. merged.append([start, end]) return merged✅ Submit now — all tests should pass.
Intuition & how it works
Imagine strips of masking tape tossed onto a ruler at random positions, where each strip represents a closed interval [start, end] (an interval that includes both endpoints, so [2, 7] and [7, 10] touch at 7 and form one continuous strip [2, 10]). Spotting which strips connect while they sit in random order is messy, so you first line all strips up by their left edge (start) from left to right. Once sorted, a single greedy sweep (one left-to-right pass that makes local decisions without ever backtracking) suffices: keep a finger on the right edge of your current merged strip, extend it whenever the next strip starts at or before your finger, and start a brand-new strip whenever a gap appears.
Why do obvious alternatives fail? Repeatedly scanning all pairs of intervals for overlaps without sorting first can take O(n^2) checks per merge and O(n^3) time overall, which times out on 10,000 intervals. Another common trap is sorting first but comparing interval i only against sorted_intervals[i - 1] instead of merged[-1]: on [[1, 12], [2, 4], [6, 8]], [6, 8] does not touch [2, 4], yet both sit completely inside [1, 12].
Let's trace intervals = [[6, 9], [1, 4], [3, 5]]:
1. Sort by start coordinate -> [[1, 4], [3, 5], [6, 9]], and start merged = [[1, 4]].
2. Next is [3, 5]: 3 <= 4, so it overlaps [1, 4] and extends it to [1, max(4, 5)] = [1, 5].
3. Next is [6, 9]: 6 > 5, so [1, 5] is finished and merged becomes [[1, 5], [6, 9]].
Complexity
Let n be len(intervals).
- Time:
O(n log n), becausesorted(intervals)uses Timsort (Python's built-in hybrid merge-and-insertion sorting algorithm) to order thentwo-element lists inO(n log n)comparisons, and the single sweep afterward visits each of thenintervals once withO(1)comparisons and list appends per step. - Space:
O(n), becausesorted(intervals)allocates a list ofnreferences andmergedholds up tontwo-element lists when all input intervals are disjoint.
Edge cases
- Empty list (
[]): Caught immediately byif not intervals: return []. - Single interval (
[[4, 7]]): Loop oversorted_intervals[1:]does zero iterations and returns a fresh copy[[4, 7]]. - Touching endpoints (
[[2, 7], [7, 10]]):7 <= 7evaluates toTrue, merging them into[[2, 10]]. - Adjacent integers with a gap (
[[1, 2], [3, 4]]): No real number belongs to both[1, 2]and[3, 4](3 > 2), so they remain separate. - Nested intervals (
[[2, 7], [3, 5]]):max(7, 5)preserves7instead of shrinking the right edge to5. - Duplicate and zero-length point intervals (
[[0, 0], [0, 0], [5, 5], [5, 9]]): Handled seamlessly bystart <= last_endandmax(...), producing[[0, 0], [5, 9]].
Common mistakes
- Forgetting to sort
intervalsfirst: Only merges intervals that happen to sit next to each other in the raw input. - Writing
start < last_endinstead ofstart <= last_end: Leaves touching intervals like[2, 7]and[7, 10]unmerged and fails Example 2. - Writing
last_merged[1] = endwithoutmax(last_end, end): Truncates[2, 7]to[2, 5]whenever a shorter nested interval[3, 5]follows it. - Comparing
sorted_intervals[i]tosorted_intervals[i - 1]instead ofmerged[-1]: Misses overlaps whenever a short nested interval sits between a long outer interval and another inner interval. - Mutating the caller's inner
[start, end]lists directly: Appendingsorted_intervals[0]without copying[first_start, first_end]meanslast_merged[1] = ...silently modifies the caller's original list object.
Alternative approaches
- Coordinate bucketing (
O(n + M)using the bounded range0 <= end <= 10^4): Create an arraymax_end_at_startof sizeM = 10,001initialized to-1, record the largestendfor eachstartinO(n), and sweepxfrom0to10,000extending or closing the active block. This avoids theO(n log n)comparison sort when coordinates are small non-negative integers, though it breaks or wastes memory if coordinates can be negative, floating-point, or large timestamps.
Follow-up questions
- Can you analyze the runtime and memory cost, and reduce auxiliary memory if mutating the input list is allowed? Our solution runs in
O(n log n)time andO(n)space. If the caller permits an in-place algorithm (an algorithm that overwrites the input list directly rather than allocating a separate output list), callintervals.sort()and maintain awriteindex at the front ofintervals: extendintervals[write - 1][1]on overlap, or store[start, end]intointervals[write]and incrementwrite, then slice away the tail withdel intervals[write:]. Aside from the sorting routine's internal workspace (up toO(n)temporary pointers in Python's Timsort, orO(1)extra space with heapsort), our merge pass usesO(1)auxiliary variables.
python
def merge_in_place(intervals):
intervals.sort()
write = 0
for start, end in intervals:
if write > 0 and start <= intervals[write - 1][1]:
intervals[write - 1][1] = max(intervals[write - 1][1], end)
else:
intervals[write] = [start, end]
write += 1
del intervals[write:]
return intervals
- How would you adapt this algorithm for billions of timestamp ranges stored on disk that exceed available RAM? Switching from small integers to arbitrary timestamps leaves
start <= last_endandmax(last_end, end)unchanged (once endpoint inclusivity is agreed upon). Because the dataset exceeds RAM, replace in-memorysorted()with external merge sort (reading RAM-sized chunks from disk, sorting each chunk in memory, writing sorted run files back to disk, and streaming all runs together through a min-heap — a binary tree structure that pops the earliest-starting interval next). As the min-heap yields intervals in ascendingstartorder, the merge step keeps just one active[cur_start, cur_end]pair in memory (O(1)RAM) and flushes each completed range to output storage wheneverstart > cur_end. - If the intervals arrive pre-sorted by start coordinate, how fast can you merge them? Skip
sorted(intervals)altogether and run only Phase 2's single left-to-right pass, lowering total time fromO(n log n)toO(n)withO(1)extra workspace beyond the output list.O(n)is optimal because every interval must be inspected at least once to verify whether it extends or separates from its predecessor.
Follow-up questions
- Can you analyze the runtime and memory cost, and reduce auxiliary memory if mutating the input list is allowed?
- How would you adapt this algorithm for billions of timestamp ranges stored on disk that exceed available RAM?
- If the intervals arrive pre-sorted by start coordinate, how fast can you merge them?
Similar questions
- Minimum Tennis Courts for Concurrent Reservations
- Minimum Court Allocation for Match Reservations
- Fixed-Window Moving Average Over a Numeric Stream
- Reciprocal-Depth Sum of Nested Lists
- Sliding-Window Mean Over an Integer Stream
- Segment-Trie Path Router with Single-Segment Wildcards
More Atlassian interview questions
- Per-User Rolling-Window Rate Limiter Medium
- Minimum Court Allocation for Match Reservations Medium
- Two-by-Three React Feed Grid: Static Data, API Fetch, and Hooks Hard Pro
- Design a Trending Workspace Content Leaderboard Medium Pro
- Frontend Architecture for Live Search Over an Unbounded Catalog Hard Pro
- Music Playback State Machine with Queue, Loop, and Shuffle Medium Pro
- Distributed API Rate Limiter Architecture Easy Pro
- Post Comments and Notification Architecture Medium Pro
- Multi-Tenant Tagging Service and REST API Medium Pro
- Hybrid RBAC and Resource ACL Authorization Service Medium Pro