Interval Merging and Sorted Insertion
Medium · Coding & Algorithms · Data Engineer · Technical Screen
Problem Statement
Work through two closely related problems on closed integer intervals [start, end] (where both endpoints start and end belong to the interval, so [a, b] and [b, c] share point b and combine into [a, c]):
- Part 1 — Consolidate arbitrary intervals (conceptual warm-up): Given an array of closed integer ranges in any order, describe how to combine all overlapping or endpoint-touching ranges into a sorted list of disjoint ranges (for instance,
[[10, 14], [2, 5], [4, 9], [18, 20]]consolidates to[[2, 9], [10, 14], [18, 20]]). - Part 2 — Insert one range into sorted disjoint intervals (implemented in
insert_interval): Given an arrayintervalsof pairwise non-overlapping closed intervals already ordered by ascendingstart, along with a single closed intervalnew_interval = [start, end], insertnew_intervalinto the schedule and merge any intervals that overlap or touch it. Return the resulting list of disjoint intervals in ascending order.
Implement insert_interval(intervals, new_interval) so that empty schedules, insertions before the first or after the last element, full containment, and shared-endpoint merges are all handled cleanly.
Examples
Example 1
Input: intervals = [[0, 2], [4, 6], [8, 9], [11, 15], [18, 22]], new_interval = [5, 11]
Output: [[0, 2], [4, 15], [18, 22]]
[0, 2] finishes before 5 and stays unchanged. [5, 11] overlaps [4, 6], completely covers [8, 9], and shares endpoint 11 with [11, 15], merging all three into [4, 15], while [18, 22] starts past 15 and stays separate.
Example 2
Input: intervals = [], new_interval = [10, 14]
Output: [[10, 14]]
When no existing intervals are present, the output contains [10, 14] alone.
Example 3
Input: intervals = [[2, 6], [10, 13]], new_interval = [4, 8]
Output: [[2, 8], [10, 13]]
[4, 8] overlaps [2, 6] to form [2, 8], which still ends strictly before [10, 13] begins.
Example 4
Input: intervals = [[7, 10], [12, 16]], new_interval = [1, 4]
Output: [[1, 4], [7, 10], [12, 16]]
[1, 4] finishes strictly before [7, 10] starts, so it is placed at the front without merging.
Constraints
0 <= len(intervals) <= 10^5len(intervals[i]) == 2with-10^9 <= intervals[i][0] <= intervals[i][1] <= 10^9intervalsis sorted in strictly disjoint ascending order:intervals[i][1] < intervals[i + 1][0]for every0 <= i < len(intervals) - 1len(new_interval) == 2with-10^9 <= new_interval[0] <= new_interval[1] <= 10^9
Step-by-step walkthrough
Understand the two interval tasks and endpoint rules
We have two classic interval problems on integer ranges
[start, end]withstart <= end:- Part 1 — Consolidate arbitrary intervals: Given a list of intervals in any order, return a sorted list where all overlapping or touching intervals have been combined.
- Part 2 — Insert one interval (judged via
insert_interval): Given an already sorted, non-overlapping list of intervals plus onenew_interval, insertnew_intervaland merge any overlaps so the returned list remains sorted and conflict-free.
Before writing a line of code, check what happens when two intervals touch at a single endpoint! In Example 1 (
new_interval = [5, 11]inserted into..., [11, 15], ...),[5, 11]and[11, 15]touch only at11and still merge into[4, 15]. That confirms the intervals are closed intervals (bothstartandendare included):[5, 11]and[11, 15]share the point11-> merge into[5, 15].[0, 2]and[4, 6]have a gap between2and4and share no point -> stay separate.
Part 1: Sort by start time, then sweep left to right
If intervals arrive unsorted, overlapping ranges can be scattered anywhere in the array, and comparing every pair would take
O(N^2)time. Sorting bystartputs overlapping intervals right next to each other on the number line:Sorted input: [2, 5] [10, 14] [18, 20] [4, 9] 2--4--5--9 10----14 18----20 \______/ [2, 9] [10, 14] [18, 20]Once sorted, we keep a
mergedlist and inspect each[current_start, current_end]from left to right. Because every earlier interval inmergedended strictly beforemerged[-1]started, the only intervalcurrentcan possibly overlap islast_interval = merged[-1]:- If
current_start <= last_interval[1], they overlap or touch: extendlast_interval[1] = max(last_interval[1], current_end). We must usemax(...)because[1, 10]followed by[2, 5]swallows[2, 5]completely and must keep10, not shrink to5. - Otherwise
current_start > last_interval[1], so a gap exists and we append[current_start, current_end]as a brand-new range.
def merge_intervals(intervals: List[List[int]]) -> List[List[int]]: """Task 1: Merge overlapping closed intervals given in arbitrary order.""" if not intervals: return [] # Sort by start time (and by end time on ties) so overlapping intervals sit side by side. sorted_intervals = sorted(intervals) # merged: list of [start, end] pairs built left to right; copy the first so input is never mutated. merged: List[List[int]] = [[sorted_intervals[0][0], sorted_intervals[0][1]]] for current_start, current_end in sorted_intervals[1:]: last_interval = merged[-1] # Closed intervals touch or overlap whenever current_start <= last_interval[1]. if current_start <= last_interval[1]: # Use max() because [1, 10] followed by [2, 5] must keep end = 10, not shrink to 5. last_interval[1] = max(last_interval[1], current_end) else: merged.append([current_start, current_end]) return merged- If
Part 2: Split the sorted timeline into three clean zones
We could solve Part 2 by appending
new_intervaltointervalsand callingmerge_intervals. That is100%valid as a quick sanity check, but re-sorting throws away the fact thatintervalsis already sorted and non-overlapping, payingO(N log N)when a singleO(N)pass is enough.Picture
new_interval = [merged_start, merged_end]dropped onto the sorted timeline. Every existing interval falls into one of three consecutive zones:Existing: [0, 2] [4, 6] [8, 9] [11, 15] [18, 22] New: [5, --------- 11] Zone: |-- Left --|----- Overlapping -----|--- Right ---| Rule: end < 5 start <= 11 start > 15 Result: [0, 2] [4, 15] [18, 22]- Zone 1 — Strictly to the left (
intervals[i][1] < merged_start): Ends beforenew_intervaleven begins. Copy straight intoresult. - Zone 2 — Overlapping (
intervals[i][0] <= merged_end): Why is checkingintervals[i][0] <= merged_endsufficient here? Because any interval that survived Zone 1 already satisfiesintervals[i][1] >= merged_start! Two closed intervals[a, b]and[c, d]intersect wheneverb >= canda <= d, so every interval in Zone 2 touches or overlaps[merged_start, merged_end]. Absorb each one by wideningmerged_start = min(...)andmerged_end = max(...), then append[merged_start, merged_end]once. - Zone 3 — Strictly to the right (everything left over): Starts strictly after
merged_end. Copy straight intoresult.
- Zone 1 — Strictly to the left (
Code the three-phase O(N) sweep for insert_interval
Three sequential
whileloops sharing a single indexistep throughintervalsonce without any specialifbranches for empty inputs or insertions at the very front or very back — if a zone has zero intervals, itswhileloop simply runs zero times! We also allocate fresh[start, end]pairs so the caller's input lists are never modified in place.def insert_interval(intervals: List[List[int]], new_interval: List[int]) -> List[List[int]]: """Task 2: Insert one closed interval into a sorted, non-overlapping interval list in O(N).""" # result: new sorted, non-overlapping list of [start, end] pairs. result: List[List[int]] = [] merged_start, merged_end = new_interval[0], new_interval[1] i = 0 n = len(intervals) # Phase 1 (Strictly left): Intervals ending strictly before merged_start cannot touch new_interval. # Strict '<' is essential: if intervals[i][1] == merged_start, they share a point and must merge. while i < n and intervals[i][1] < merged_start: result.append([intervals[i][0], intervals[i][1]]) i += 1 # Phase 2 (Overlapping): Every interval reaching here has intervals[i][1] >= merged_start. # As long as intervals[i][0] <= merged_end, it shares at least one point with [merged_start, merged_end]. while i < n and intervals[i][0] <= merged_end: merged_start = min(merged_start, intervals[i][0]) merged_end = max(merged_end, intervals[i][1]) i += 1 result.append([merged_start, merged_end]) # Phase 3 (Strictly right): Remaining intervals start strictly after merged_end and stay unchanged. while i < n: result.append([intervals[i][0], intervals[i][1]]) i += 1 return resultTrace Example 1 and boundary cases
Let's trace
intervals = [[0, 2], [4, 6], [8, 9], [11, 15], [18, 22]]withnew_interval = [5, 11]:Start: merged = [5, 11], i = 0, result = [] Phase 1 (intervals[i][1] < 5): i=0: [0, 2] -> end 2 < 5 -> result = [[0, 2]], i = 1 i=1: [4, 6] -> end 6 < 5 is False -> stop Phase 1 Phase 2 (intervals[i][0] <= merged_end): i=1: [4, 6] -> start 4 <= 11 -> merged = [min(5,4), max(11,6)] = [4, 11], i = 2 i=2: [8, 9] -> start 8 <= 11 -> merged = [min(4,8), max(11,9)] = [4, 11], i = 3 i=3: [11, 15] -> start 11 <= 11 -> merged = [min(4,11), max(11,15)] = [4, 15], i = 4 i=4: [18, 22] -> start 18 <= 15 is False -> stop Phase 2 append merged -> result = [[0, 2], [4, 15]] Phase 3 (remaining): i=4: [18, 22] -> result = [[0, 2], [4, 15], [18, 22]], i = 5Quick check on the boundary cases: - Empty input (
intervals = [],new = [10, 14]): All threewhileloops skip;result.append([10, 14])returns[[10, 14]]. - Insert at start ([[7, 10], [12, 16]],new = [1, 4]): Phase 1 and Phase 2 skip (7 <= 4isFalse),[1, 4]is appended first, then Phase 3 copies[7, 10], [12, 16]. - Full containment ([[0, 2], [4, 15]],new = [8, 9]): Phase 1 copies[0, 2], Phase 2 widens[8, 9]with[4, 15]to[4, 15], returning[[0, 2], [4, 15]].Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def merge_intervals(intervals: List[List[int]]) -> List[List[int]]: """Task 1: Merge overlapping closed intervals given in arbitrary order.""" if not intervals: return [] # Sort by start time (and by end time on ties) so overlapping intervals sit side by side. sorted_intervals = sorted(intervals) # merged: list of [start, end] pairs built left to right; copy the first so input is never mutated. merged: List[List[int]] = [[sorted_intervals[0][0], sorted_intervals[0][1]]] for current_start, current_end in sorted_intervals[1:]: last_interval = merged[-1] # Closed intervals touch or overlap whenever current_start <= last_interval[1]. if current_start <= last_interval[1]: # Use max() because [1, 10] followed by [2, 5] must keep end = 10, not shrink to 5. last_interval[1] = max(last_interval[1], current_end) else: merged.append([current_start, current_end]) return merged def insert_interval(intervals: List[List[int]], new_interval: List[int]) -> List[List[int]]: """Task 2: Insert one closed interval into a sorted, non-overlapping interval list in O(N).""" # result: new sorted, non-overlapping list of [start, end] pairs. result: List[List[int]] = [] merged_start, merged_end = new_interval[0], new_interval[1] i = 0 n = len(intervals) # Phase 1 (Strictly left): Intervals ending strictly before merged_start cannot touch new_interval. # Strict '<' is essential: if intervals[i][1] == merged_start, they share a point and must merge. while i < n and intervals[i][1] < merged_start: result.append([intervals[i][0], intervals[i][1]]) i += 1 # Phase 2 (Overlapping): Every interval reaching here has intervals[i][1] >= merged_start. # As long as intervals[i][0] <= merged_end, it shares at least one point with [merged_start, merged_end]. while i < n and intervals[i][0] <= merged_end: merged_start = min(merged_start, intervals[i][0]) merged_end = max(merged_end, intervals[i][1]) i += 1 result.append([merged_start, merged_end]) # Phase 3 (Strictly right): Remaining intervals start strictly after merged_end and stay unchanged. while i < n: result.append([intervals[i][0], intervals[i][1]]) i += 1 return result✅ Submit now — all tests should pass.
Intuition & how it works
Think of intervals as paper sticky notes placed along a wall calendar timeline. In Task 1 (Merge), the sticky notes are scattered in random order; once you line them up from earliest start time to latest, any notes that touch or overlap are guaranteed to sit right next to each other, so one left-to-right sweep-line pass (scanning sorted items in order while updating only the most recent active range) tapes overlapping notes into single longer blocks. In Task 2 (Insert), the wall calendar is already tidy and conflict-free, and you only want to place one new sticky note onto it — every note completely to the left stays put, every note your new note touches gets absorbed into one combined block, and every note completely to the right stays put.
Why do naive approaches fall short? Checking every pair of intervals for overlaps without sorting takes O(N^2) time because an overlap could hide anywhere in the array. And in Task 2, tossing new_interval onto the end of intervals and re-sorting takes O(N log N) time, wasting the fact that all N input intervals were already sorted and non-overlapping.
Let's walk through inserting new_interval = [5, 11] into intervals = [[0, 2], [4, 6], [11, 15], [18, 22]], where each [start, end] is a closed interval (meaning both endpoints start and end are included in the range):
1. Phase 1 (end < 5, strictly left):
[0, 2] ends at 2 < 5 -> keep [0, 2]
[4, 6] ends at 6 >= 5 -> stop Phase 1
2. Phase 2 (start <= merged_end, overlapping or touching):
[4, 6] starts at 4 <= 11 -> widen [5, 11] to [4, 11]
[11, 15] starts at 11 <= 11 -> touches at 11! widen [4, 11] to [4, 15]
[18, 22] starts at 18 > 15 -> stop Phase 2, emit [4, 15]
3. Phase 3 (everything remaining, strictly right):
[18, 22] -> keep [18, 22]
Final output: [[0, 2], [4, 15], [18, 22]]
Complexity
Let N be the number of intervals in intervals.
- Task 1 (
merge_intervals):- Time:
O(N log N). Sorting theNintervals by start time takesO(N log N)comparisons, and the single left-to-right merge sweep visits each interval once inO(N). - Space:
O(N). Storingsorted_intervalsand themergedoutput list usesO(N)memory.
- Time:
- Task 2 (
insert_interval):- Time:
O(N). A single indexiadvances monotonically across the threewhileloops from0toN, visiting each input interval exactly once. - Space:
O(N)for the returned list (O(1)auxiliary space). Aside from the required output array, we only keep a handful of integer variables (i,n,merged_start,merged_end).
- Time:
Edge cases
- Empty input list (
intervals = []):merge_intervalsreturns[];insert_interval([], [10, 14])skips all threewhileloops and appends[[10, 14]]. - Insertion before all intervals or after all intervals: Either Phase 1 or Phase 3 runs zero iterations while Phase 2 emits
new_intervalunchanged in the exact sorted slot ([[7, 10], [12, 16]]+[1, 4]->[[1, 4], [7, 10], [12, 16]]). - One interval completely inside another:
[1, 10]followed by[2, 5](or inserting[8, 9]into[[4, 15]]) stays[1, 10]/[[4, 15]]because we update the end withmax(...)and the start withmin(...). - New interval swallowing the entire list: Inserting
[0, 10]into[[1, 2], [3, 5], [6, 7]]pulls every interval into Phase 2 and returns[[0, 10]]. - Touching endpoints vs unit gap: Closed intervals
[1, 3]and[3, 4]share point3and merge into[1, 4], whereas[1, 2]and[3, 4]share no point and remain separate. - Single-point and negative intervals: Zero-length ranges like
[-3, -3]and negative coordinates obey the exact same inequality checks without special cases.
Common mistakes
- Overwriting the end without
max(): Writinglast_interval[1] = current_endinstead ofmax(last_interval[1], current_end)shrinks[1, 10]down to[1, 3]when[2, 3]comes next. - Using
<=instead of<in Phase 1 (intervals[i][1] <= merged_start): That treats[1, 3]as strictly left of[3, 4]and fails to merge touching closed intervals. - Using
<instead of<=in Phase 2 (intervals[i][0] < merged_end): That misses intervals that start right on the boundary, such as[11, 15]meeting[4, 11]at11in Example 1. - Mutating the caller's nested lists: Appending
sorted_intervals[0]directly intomergedand mutatinglast_interval[1]modifies the caller's original[start, end]sublist in place; copying[start, end]prevents side effects.
Alternative approaches
- Append and call
merge_intervalsfor Part 2: Very short to code and impossible to get boundary indices wrong, at the cost ofO(N log N)time instead ofO(N). - Binary search for the overlap boundaries (
bisect): You can locate the first interval withend >= new_startand the first interval withstart > new_endinO(log N)binary-search steps, though building a new Pythonlist(or slicing/splicing a contiguous array) still copiesO(N)elements.
Follow-up questions
- How do the boundary comparisons change for half-open ranges [start, end) or adjacent integer days? A half-open interval
[start, end)includesstartbut excludesend, so[1, 2)and[2, 3)share zero points; if adjacent half-open ranges should stay separate, flip the touching comparisons tointervals[i][1] <= merged_startin Phase 1 andintervals[i][0] < merged_endin Phase 2 (andcurrent_start < last_interval[1]in Part 1). Conversely, for discrete integer days where day2and day3have no gap between them, merge whenevercurrent_start <= merged_end + 1. Always clarify which interval convention applies before coding. - Which data structure supports fast interleaved interval insertions and overlap lookups on a live stream? Rebuilding a Python list costs
O(N)per insertion because array elements shift in memory. Instead, store the disjoint intervals keyed bystartin a balanced binary search tree (a self-balancing tree such as Java'sTreeMapor C++'sstd::mapthat finds neighbors, inserts, and deletes inO(log N)time). Each insertion locates the predecessor/successor inO(log N)and deletesKabsorbed intervals inO((K + 1) log N); since every interval can be deleted at most once across the stream, amortized update time isO(log N). - How can you merge billions of unsorted intervals when the dataset exceeds available RAM? Use an external sort (splitting the file into RAM-sized chunks, sorting each chunk on disk, and merging the sorted streams with a min-heap) ordered by
start, then run Part 1's sweep streaming one record at a time — it holds only the single active[merged_start, merged_end]pair inO(1)memory before flushing completed ranges to output. In a SQL data warehouse, you implement the exact same sweep with a window function (a SQL calculation across ordered neighboring rows without collapsing them): compute the runningMAX(end)over all preceding rows ordered bystart, mark a new island wheneverstart > prev_max_end, sum those markers into anisland_id, andGROUP BY island_idtakingMIN(start)andMAX(end).
Follow-up questions
- How do the boundary comparisons change for half-open ranges [start, end) or adjacent integer days?
- Which data structure supports fast interleaved interval insertions and overlap lookups on a live stream?
- How can you merge billions of unsorted intervals when the dataset exceeds available RAM?
Similar questions
- 2D Canvas Editor with Undo and Redo
- Custom Array Sort and Sorted Set Intersection
- Org-Chart Path Length and Squared-Digit Convergence
- Behavioral Evidence of UBS Cultural Alignment
- Quantitative Market Modeling, Transferable Skills, and Industry Outlook
- Ten-Year Outlook for Quantitative Finance
More BlackRock interview questions
- Behavioral Evidence of UBS Cultural Alignment Medium
- Quantitative Market Modeling, Transferable Skills, and Industry Outlook Easy
- 2D Canvas Editor with Undo and Redo Easy Pro
- Ten-Year Outlook for Quantitative Finance Medium Pro
- Classify Claims from a Business Metrics Passage Easy Pro
- Custom Array Sort and Sorted Set Intersection Medium Pro
- Org-Chart Path Length and Squared-Digit Convergence Medium Pro
- Motivation for BlackRock and Off-CV Narrative Easy Pro