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]):

  1. 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]]).
  2. Part 2 — Insert one range into sorted disjoint intervals (implemented in insert_interval): Given an array intervals of pairwise non-overlapping closed intervals already ordered by ascending start, along with a single closed interval new_interval = [start, end], insert new_interval into 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^5
  • len(intervals[i]) == 2 with -10^9 <= intervals[i][0] <= intervals[i][1] <= 10^9
  • intervals is sorted in strictly disjoint ascending order: intervals[i][1] < intervals[i + 1][0] for every 0 <= i < len(intervals) - 1
  • len(new_interval) == 2 with -10^9 <= new_interval[0] <= new_interval[1] <= 10^9

Step-by-step walkthrough

  1. Understand the two interval tasks and endpoint rules

    We have two classic interval problems on integer ranges [start, end] with start <= end:

    1. 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.
    2. Part 2 — Insert one interval (judged via insert_interval): Given an already sorted, non-overlapping list of intervals plus one new_interval, insert new_interval and 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 at 11 and still merge into [4, 15]. That confirms the intervals are closed intervals (both start and end are included):

    • [5, 11] and [11, 15] share the point 11 -> merge into [5, 15].
    • [0, 2] and [4, 6] have a gap between 2 and 4 and share no point -> stay separate.
  2. 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 by start puts 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 merged list and inspect each [current_start, current_end] from left to right. Because every earlier interval in merged ended strictly before merged[-1] started, the only interval current can possibly overlap is last_interval = merged[-1]:

    • If current_start <= last_interval[1], they overlap or touch: extend last_interval[1] = max(last_interval[1], current_end). We must use max(...) because [1, 10] followed by [2, 5] swallows [2, 5] completely and must keep 10, not shrink to 5.
    • 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
    
  3. Part 2: Split the sorted timeline into three clean zones

    We could solve Part 2 by appending new_interval to intervals and calling merge_intervals. That is 100% valid as a quick sanity check, but re-sorting throws away the fact that intervals is already sorted and non-overlapping, paying O(N log N) when a single O(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]
    
    1. Zone 1 — Strictly to the left (intervals[i][1] < merged_start): Ends before new_interval even begins. Copy straight into result.
    2. Zone 2 — Overlapping (intervals[i][0] <= merged_end): Why is checking intervals[i][0] <= merged_end sufficient here? Because any interval that survived Zone 1 already satisfies intervals[i][1] >= merged_start! Two closed intervals [a, b] and [c, d] intersect whenever b >= c and a <= d, so every interval in Zone 2 touches or overlaps [merged_start, merged_end]. Absorb each one by widening merged_start = min(...) and merged_end = max(...), then append [merged_start, merged_end] once.
    3. Zone 3 — Strictly to the right (everything left over): Starts strictly after merged_end. Copy straight into result.
  4. Code the three-phase O(N) sweep for insert_interval

    Three sequential while loops sharing a single index i step through intervals once without any special if branches for empty inputs or insertions at the very front or very back — if a zone has zero intervals, its while loop 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 result
    
  5. Trace Example 1 and boundary cases

    Let's trace intervals = [[0, 2], [4, 6], [8, 9], [11, 15], [18, 22]] with new_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 = 5
    

    Quick check on the boundary cases: - Empty input (intervals = [], new = [10, 14]): All three while loops 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 <= 4 is False), [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]].

  6. 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 the N intervals by start time takes O(N log N) comparisons, and the single left-to-right merge sweep visits each interval once in O(N).
    • Space: O(N). Storing sorted_intervals and the merged output list uses O(N) memory.
  • Task 2 (insert_interval):
    • Time: O(N). A single index i advances monotonically across the three while loops from 0 to N, 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).

Edge cases

  • Empty input list (intervals = []): merge_intervals returns []; insert_interval([], [10, 14]) skips all three while loops 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_interval unchanged 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 with max(...) and the start with min(...).
  • 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 point 3 and 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(): Writing last_interval[1] = current_end instead of max(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] at 11 in Example 1.
  • Mutating the caller's nested lists: Appending sorted_intervals[0] directly into merged and mutating last_interval[1] modifies the caller's original [start, end] sublist in place; copying [start, end] prevents side effects.

Alternative approaches

  • Append and call merge_intervals for Part 2: Very short to code and impossible to get boundary indices wrong, at the cost of O(N log N) time instead of O(N).
  • Binary search for the overlap boundaries (bisect): You can locate the first interval with end >= new_start and the first interval with start > new_end in O(log N) binary-search steps, though building a new Python list (or slicing/splicing a contiguous array) still copies O(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) includes start but excludes end, so [1, 2) and [2, 3) share zero points; if adjacent half-open ranges should stay separate, flip the touching comparisons to intervals[i][1] <= merged_start in Phase 1 and intervals[i][0] < merged_end in Phase 2 (and current_start < last_interval[1] in Part 1). Conversely, for discrete integer days where day 2 and day 3 have no gap between them, merge whenever current_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 by start in a balanced binary search tree (a self-balancing tree such as Java's TreeMap or C++'s std::map that finds neighbors, inserts, and deletes in O(log N) time). Each insertion locates the predecessor/successor in O(log N) and deletes K absorbed intervals in O((K + 1) log N); since every interval can be deleted at most once across the stream, amortized update time is O(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 in O(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 running MAX(end) over all preceding rows ordered by start, mark a new island whenever start > prev_max_end, sum those markers into an island_id, and GROUP BY island_id taking MIN(start) and MAX(end).

Follow-up questions

Similar questions

More BlackRock interview questions

All 9 BlackRock questions →