Consolidate Overlapping Closed Intervals

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Given a collection of closed intervals intervals, where each element intervals[i] = [start_i, end_i] spans every value from start_i through end_i inclusive, consolidate all overlapping ranges and return the resulting disjoint intervals sorted by ascending start.

Two closed intervals [a, b] and [c, d] ordered with a <= c overlap whenever c <= b:

  • Ranges that touch at a single boundary coordinate (such as [0, 6] and [6, 11]) share that coordinate and combine into [0, 11].
  • Ranges separated by a positive gap (such as [3, 6] and [7, 9]) share no common value and remain distinct entries in the output.

Implement merge_intervals(intervals) without assuming any particular ordering of the input list.

Examples

Example 1

Input: intervals = [[12, 16], [2, 5], [4, 9], [20, 25], [5, 7]]
Output: [[2, 9], [12, 16], [20, 25]]

Walk-through: Sorting by start point orders the ranges as [2, 5], [4, 9], [5, 7], [12, 16], [20, 25]. First [2, 5] and [4, 9] combine into [2, 9], which then absorbs [5, 7]. Neither [12, 16] nor [20, 25] intersects any other range, so three disjoint intervals are returned.

Example 2

Input: intervals = [[0, 6], [6, 11]]
Output: [[0, 11]]

Walk-through: Because intervals are closed on both ends, the point 6 belongs to both [0, 6] and [6, 11], fusing them into [0, 11].

Example 3

Input: intervals = [[7, 9], [3, 6]]
Output: [[3, 6], [7, 9]]

Walk-through: No number satisfies both x <= 6 and x >= 7. Sorting places [3, 6] ahead of [7, 9] while keeping both intervals separate.

Constraints

  • 0 <= len(intervals) <= 100_000
  • len(intervals[i]) == 2 for every i
  • -10^9 <= start_i <= end_i <= 10^9
  • Input elements can appear in any order, including duplicates and zero-length point intervals (start_i == end_i).

Step-by-step walkthrough

  1. Understand the overlap rule on a number line

    We receive up to 100,000 closed intervals [start, end] in arbitrary order. Because a closed interval includes both endpoints, [0, 6] contains 0, 6, and every value between them. Our job is to fuse all intersecting ranges and return a sorted list of disjoint intervals (ranges that share zero points).

    Sketching the four geometric situations on a number line pins down the exact merge rule:

    Number line:   0   1   2   3   4   5   6   7   8   9  10  11
                   |---|---|---|---|---|---|---|---|---|---|---|
    
    Case A (partial overlap):
      [2, 5]               [===========]
      [4, 9]                       [===================]
      Merged ->            [===========================]          -> [2, 9]
    
    Case B (shared endpoint):
      [0, 6]       [=======================]
      [6, 11]                              [===================]
      Merged ->    [===========================================]  -> [0, 11]  (6 is in both!)
    
    Case C (fully nested):
      [2, 9]               [===========================]
      [5, 7]                           [=======]
      Merged ->            [===========================]          -> [2, 9]
    
    Case D (unit gap, no shared point):
      [3, 6]                   [===========]
      [7, 9]                                   [=======]
      Merged ->                [===========]   [=======]          -> [[3, 6], [7, 9]]
    

    Whenever two closed ranges [a, b] and [c, d] are ordered so a <= c, they share at least one coordinate if and only if c <= b.

  2. Why brute-force pairwise merging is too slow

    A straightforward trial method scans all pairs in the list, replaces any overlapping pair [a, b] and [c, d] (a <= d and c <= b) with [min(a, c), max(b, d)], and repeats passes until a full scan finds zero overlaps.

    Although mathematically sound, each scan inspects up to O(n^2) pairs, and a long chain of merges can force up to n scans for O(n^3) worst-case work. At n = 100,000, even one O(n^2) scan performs roughly 5 * 10^9 checks and exceeds any reasonable time budget.

    That quadratic search is only needed because unsorted ranges can sit anywhere in the input array.

  3. Key insight: sort by start point first

    Sorting the intervals in ascending start order brings every merge candidate directly behind the active consolidated range.

    As we build merged from left to right, each incoming interval [curr_start, curr_end] only needs to be tested against the most recent output range merged[-1]:

    1. Every earlier range in merged ended strictly before merged[-1][0] (otherwise it would have fused with merged[-1]).
    2. Sorting guarantees curr_start >= merged[-1][0].
    3. Combining those inequalities shows curr_start lies strictly beyond every earlier range in merged, so it can never reach back to merged[-2] or earlier.

    Notice why we compare against merged[-1] rather than the previous input element:

    Sorted input:  [1, 12],  [3, 4],  [7, 9]
    
    1. Read [1, 12] -> merged = [[1, 12]]
    2. Read [3, 4]  -> 3 <= 12, so [3, 4] is absorbed -> merged = [[1, 12]]
    3. Read [7, 9]  -> compare against merged[-1] = [1, 12] (NOT [3, 4]!):
                       7 <= 12, so [7, 9] is absorbed -> merged = [[1, 12]]
    

    Calling sorted(intervals) in Python builds a new list ordered by start (and end on ties) without reordering the caller's list:

    if not intervals:
        return []
    
    # Phase 1: Sort intervals by [start, end] ascending without mutating the caller's list.
    sorted_intervals = sorted(intervals)
    
    # merged: list of disjoint [start, end] ranges sorted by start, e.g. [[2, 9], [12, 16]].
    merged: List[List[int]] = []
    
  4. Sweep left to right and avoid three classic bugs

    For each interval in sorted_intervals, we compare curr_start with last_end = merged[-1][1]:

    • Use <=, not <: When curr_start == last_end (as in [0, 6] and [6, 11]), both closed ranges contain that shared endpoint and must fuse.
    • Extend the end with max(last_end, curr_end): When a shorter interval sits completely inside the active range (such as [5, 7] inside [2, 9]), assigning last_merged[1] = curr_end directly would shrink [2, 9] down to [2, 7]. Taking max keeps 9.
    • Append a fresh [curr_start, curr_end] list: Appending interval directly (merged.append(interval)) would alias the caller's inner list, causing later edits to last_merged[1] to mutate the caller's input data.
    # Phase 2: Sweep left to right, comparing each interval only against the last merged range.
    for interval in sorted_intervals:
        curr_start = interval[0]
        curr_end = interval[1]
    
        if not merged:
            # Copy into a fresh [start, end] list so later updates never mutate the caller's input.
            merged.append([curr_start, curr_end])
            continue
    
        last_merged = merged[-1]
        last_end = last_merged[1]
    
        # Use <= (not <) because closed intervals sharing one endpoint (e.g. [0, 6] and [6, 11]) overlap.
        if curr_start <= last_end:
            # Take max() so a nested interval like [5, 7] inside [2, 9] never shrinks last_end.
            last_merged[1] = max(last_end, curr_end)
        else:
            # curr_start > last_end means a gap exists, so open a new disjoint interval.
            merged.append([curr_start, curr_end])
    

    Because each new entry in merged begins at curr_start and we scan in non-decreasing start order, merged is already sorted by start when the sweep finishes.

  5. Trace the examples

    Let's walk through Example 1: intervals = [[12, 16], [2, 5], [4, 9], [20, 25], [5, 7]].

    Phase 1 (sort):
      sorted_intervals = [[2, 5], [4, 9], [5, 7], [12, 16], [20, 25]]
    
    Phase 2 (sweep):
      Step  Current    merged[-1]  Test (curr_start <= last_end?)  Action                  merged after
      ----  ---------  ----------  ------------------------------  ----------------------  ----------------------------
      1     [2, 5]     (empty)     -                               open [2, 5]             [[2, 5]]
      2     [4, 9]     [2, 5]      4 <= 5   -> True (overlap)      end = max(5, 9) = 9     [[2, 9]]
      3     [5, 7]     [2, 9]      5 <= 9   -> True (nested)       end = max(9, 7) = 9     [[2, 9]]
      4     [12, 16]   [2, 9]      12 <= 9  -> False (gap)         open [12, 16]           [[2, 9], [12, 16]]
      5     [20, 25]   [12, 16]    20 <= 16 -> False (gap)         open [20, 25]           [[2, 9], [12, 16], [20, 25]]
    

    Checking Examples 2 and 3:

    • Example 2 ([[0, 6], [6, 11]]): curr_start <= last_end evaluates 6 <= 6 (True), combining into [[0, 11]].
    • Example 3 ([[7, 9], [3, 6]]): sorting yields [[3, 6], [7, 9]], and 7 <= 6 is False, keeping [[3, 6], [7, 9]].
  6. Full solution

    Putting both phases together gives the complete implementation:

    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 intervals by [start, end] ascending without mutating the caller's list.
        sorted_intervals = sorted(intervals)
    
        # merged: list of disjoint [start, end] ranges sorted by start, e.g. [[2, 9], [12, 16]].
        merged: List[List[int]] = []
    
        # Phase 2: Sweep left to right, comparing each interval only against the last merged range.
        for interval in sorted_intervals:
            curr_start = interval[0]
            curr_end = interval[1]
    
            if not merged:
                # Copy into a fresh [start, end] list so later updates never mutate the caller's input.
                merged.append([curr_start, curr_end])
                continue
    
            last_merged = merged[-1]
            last_end = last_merged[1]
    
            # Use <= (not <) because closed intervals sharing one endpoint (e.g. [0, 6] and [6, 11]) overlap.
            if curr_start <= last_end:
                # Take max() so a nested interval like [5, 7] inside [2, 9] never shrinks last_end.
                last_merged[1] = max(last_end, curr_end)
            else:
                # curr_start > last_end means a gap exists, so open a new disjoint interval.
                merged.append([curr_start, curr_end])
    
        return merged
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine consolidating busy blocks on a daily calendar when teammates hand you sticky notes of reservation windows in random order. Each reservation is a closed interval (a range [start, end] that includes both boundary endpoints), and our goal is to produce disjoint intervals (ranges that are completely separate and share zero points). Once you line those notes up in ascending order of start time, you only ever need to watch the single busy block currently in progress: if the next window begins at or before the current block ends, you stretch the current block's end time when needed; if it begins strictly later, a genuine gap has opened, so you set the finished block aside and start a new one.

Without sorting first, overlapping windows can sit at opposite ends of the array. A naive method has to test every pair of intervals (O(n^2) checks per pass) and repeat passes whenever a newly widened block touches another interval (up to O(n^3) work overall). With n = 100,000 intervals, billions of pairwise checks are far too slow, whereas sorting once places every possible overlap right behind the active block.

Here is how sorting and sweeping processes [[12, 16], [2, 5], [4, 9], [20, 25], [5, 7]]:

  1. Sort by start coordinate: [[2, 5], [4, 9], [5, 7], [12, 16], [20, 25]].
  2. Open with [2, 5] as the active block: merged = [[2, 5]].
  3. Inspect [4, 9]: 4 <= 5 (overlaps), so update the active end to max(5, 9) = 9, giving merged = [[2, 9]].
  4. Inspect [5, 7]: 5 <= 9 (nested), and max(9, 7) = 9 keeps merged = [[2, 9]].
  5. Inspect [12, 16] (12 > 9) and [20, 25] (20 > 16): both start after a gap, finishing with [[2, 9], [12, 16], [20, 25]].

Complexity

  • Time: O(n log n) for n intervals. Sorting the n intervals by start coordinate takes O(n log n) comparisons, and the single left-to-right pass afterward inspects each interval once with O(1) comparisons and list appends per step.
  • Space: O(n). sorted(intervals) allocates an n-element sorted list (keeping the caller's input order intact), and merged holds up to n output ranges when none overlap.

Edge cases

  • Empty or single-interval input: [] returns [] immediately, and [[4, 8]] returns a fresh [[4, 8]] without needing any merge comparisons.
  • Shared single endpoint: [0, 6] and [6, 11] both contain 6, so 6 <= 6 fuses them into [0, 11].
  • Neighboring integers with no shared value: [3, 6] and [7, 9] share zero numbers (7 <= 6 is false), so they stay separate as [[3, 6], [7, 9]].
  • Fully nested intervals: [2, 9] followed by [5, 7] stays [2, 9] because max(9, 7) preserves the larger right endpoint.
  • Duplicates and tied start points: [[4, 6], [4, 6]] collapses into [[4, 6]], and equal starts like [[1, 3], [1, 8], [1, 5]] consolidate into [[1, 8]].
  • Zero-length point intervals: Single-point ranges such as [5, 5] obey the exact same curr_start <= last_end test ([5, 5] merges with [4, 6] or another [5, 5], and stays separate from [3, 3]).
  • Extreme negative and positive coordinates (-10^9 to 10^9): Endpoints are only compared with <= and max, never added or subtracted, avoiding integer overflow in fixed-width languages.

Common mistakes

  • Writing < instead of <= in the overlap test: Using curr_start < last_end misses intervals that meet at one boundary point, leaving [[0, 6], [6, 11]] split instead of combining into [[0, 11]].
  • Writing curr_start <= last_end + 1: That fuses discrete integer neighbors like [3, 6] and [7, 9], violating closed-interval semantics.
  • Assigning last_merged[1] = curr_end without max: When a shorter range [5, 7] sits inside [2, 9], omitting max accidentally truncates the active range down to [2, 7].
  • Comparing against the previous input element instead of merged[-1]: After [1, 12] and [3, 4], the next range [7, 9] does not touch [3, 4], yet it still lies inside the consolidated range [1, 12].
  • Appending the caller's inner list directly (merged.append(interval)): Later updating merged[-1][1] then silently overwrites the caller's input list.

Alternative approaches

  • Coordinate sweep-line (boundary events): Turn each [start, end] into a +1 open event at start and a -1 close event at end, sort events so opens precede closes at tied coordinates (ensuring touching endpoints fuse), and emit a range whenever the active count rises above 0 and returns to 0. This also takes O(n log n) time and O(n) space, though it sorts 2n event tuples instead of n intervals.

Follow-up questions

  • Suppose ranges arrive one by one in a live stream and callers query the consolidated set at any moment; what data structure would you maintain? Keep the active disjoint intervals ordered by start in a balanced binary search tree (a tree structure that maintains sorted order while supporting search, insertion, and deletion in O(log n) time; in Python, sortedcontainers.SortedList offers equivalent operations). When [s, e] arrives, binary search for the last stored range with start <= s (which intersects if end >= s) and walk forward across stored ranges while start <= e; remove every intersecting range found and insert a single [min_start, max_end] replacement. Although one arrival absorbing k stored intervals takes O((k + 1) log n) work, each interval is inserted once and deleted at most once, yielding O(log n) amortized time (average cost per arrival across the entire stream).
  • What changes if each pair denotes a set of integers so neighboring blocks like [2, 5] and [6, 9] also fuse into [2, 9]? Replace the overlap check curr_start <= last_end with curr_start <= last_end + 1, since no integer exists strictly between 5 and 6. Sorting by start and updating the right boundary via max(last_end, curr_end) stay unchanged. In fixed-width integer languages such as C++ or Java, write curr_start - 1 <= last_end (after guarding against curr_start == INT_MIN) so last_end + 1 cannot overflow near the maximum integer bound.
  • How can you consolidate the array in place using O(1) extra memory beyond the sorting step? Perform the consolidation in-place (reusing the input list's slots rather than building a separate output array): sort intervals directly, maintain a write cursor write_idx = 0 marking the active merged range inside intervals, and for each index i from 1 upward either update intervals[write_idx][1] = max(intervals[write_idx][1], intervals[i][1]) on overlap or increment write_idx += 1 and copy intervals[i] into intervals[write_idx], finally truncating del intervals[write_idx + 1:]. The sweep uses O(1) scalar variables, though you should note in an interview that Python's Timsort uses up to O(n) scratch memory whereas heapsort achieves strict O(1) auxiliary space in O(n log n) time, and mutating the caller's array must be explicit in the function contract.

Follow-up questions

Similar questions

More Aim Intelligent Machine interview questions

All 1 Aim Intelligent Machine questions →