Consolidate Overlapping Intervals

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

You are given an array intervals where each entry [start, end] denotes a closed numeric range covering every real number x with start <= x <= end.

Implement a function that combines all ranges that share one or more points into consolidated ranges, returning a list of mutually disjoint [start, end] pairs sorted by start in ascending order.

def merge_intervals(intervals: List[List[int]]) -> List[List[int]]:

Two ranges [a, b] and [c, d] must be combined whenever their intersection is non-empty—including when one range's right endpoint equals the other's left endpoint (b == c) or when one range lies completely inside the other. Ranges arrive in arbitrary order, and an empty input list should produce [].

Examples

Example 1

  • Input: intervals = [[12, 16], [2, 5], [4, 9], [20, 25], [5, 7]]
  • Output: [[2, 9], [12, 16], [20, 25]]
  • Explanation: Ordering by start gives [2, 5], [4, 9], [5, 7], [12, 16], [20, 25]. Ranges [2, 5] and [4, 9] overlap on [4, 5] to form [2, 9], which also absorbs the nested range [5, 7]. Neither [12, 16] nor [20, 25] intersects any other range.

Example 2

  • Input: intervals = [[6, 11], [0, 6], [14, 19]]
  • Output: [[0, 11], [14, 19]]
  • Explanation: [0, 6] and [6, 11] meet at coordinate 6, so they fuse into a single continuous range [0, 11], while [14, 19] stays separate.

Constraints

  • 0 <= len(intervals) <= 10^4
  • Each element of intervals is a two-integer list [start, end].
  • 0 <= start < end <= 10^6

Step-by-step walkthrough

  1. Understand the timeline and boundary rules

    Each [start, end] pair is a closed interval — a continuous stretch of numbers from start through end, including both endpoints. We want to combine any intervals that share at least one point into a single wider interval so the output covers the exact same points with no overlaps left.

    Visualizing the four ways two intervals can relate on a number line makes every boundary rule clear:

    1. Partial overlap:    [2----5]        and    [4-------9]    -->  merge into [2----------9]
    2. Shared boundary:    [0-------6]     and          [6--11]  -->  merge into [0----------11] (touch at 6)
    3. Nested (contained): [2-------------------9]  and [5---7]  -->  merge into [2-------------------9]
    4. Separate (gap):     [2--3]          and       [4--5]      -->  stay [2, 3], [4, 5]  (gap between 3 and 4)
    

    Notice the difference between cases 2 and 4: [0, 6] and [6, 11] share the point 6, whereas [2, 3] and [4, 5] leave the open stretch between 3 and 4 uncovered, so they must remain two separate intervals.

  2. Why comparing unsorted pairs is too slow

    When intervals arrive in arbitrary order, two intervals that belong to the same merged block can sit at opposite ends of the input list — or even need a third interval at the end of the list to bridge them together (such as [2, 5], [8, 11], and finally [4, 9]).

    A naive approach repeatedly scans all pairs (i, j), merges the first overlapping pair it finds, and restarts from the beginning until no pair overlaps. Each merge inspects up to O(n^2) pairs, and up to n - 1 merges can happen, costing O(n^3) time in the worst case. With n = 10,000 intervals, that is far too slow.

  3. Key idea: sort by start time so merges become adjacent

    If we first sort the intervals by start coordinate from smallest to largest, every group of intervals that merges together becomes one contiguous run in the sorted list.

    Why can we focus only on the very last interval in our merged output list? Suppose our last merged interval is [cur_start, cur_end] and the next sorted interval is [start, end]. Because the list is sorted, start >= cur_start is guaranteed:

    Case A: start <= cur_end (overlaps or touches)
      merged[-1]:  [cur_start --------- cur_end]
      next:                  [start ----------- end]
      --> They share at least `start`, so update cur_end = max(cur_end, end).
    
    Case B: start > cur_end (gap!)
      merged[-1]:  [cur_start ---- cur_end]
      next:                                  [start ---- end]
      every future interval:                    [>= start ...]
      --> Every later interval starts at or after `start > cur_end`,
          so NO future interval can ever reach back to `cur_end`!
          `merged[-1]` is permanently finished, and `[start, end]` starts a new block.
    
  4. Write the single-pass sweep

    Python's built-in sorted(intervals) compares 2-element lists in lexicographical order (dictionary order: comparing index 0 first, and breaking ties with index 1), which sorts by start ascending without needing a custom key function.

    Two details keep the loop bug-free:

    1. Copy [start, end] when starting a new block: writing merged.append([start, end]) allocates a fresh 2-element list, so updating merged[-1][1] later never mutates the caller's original input lists.
    2. Keep the larger endpoint with max(merged[-1][1], end): if [5, 7] comes right after [2, 9], max(9, 7) keeps 9 instead of shrinking the block to 7.
    def merge_intervals(intervals: List[List[int]]) -> List[List[int]]:
        # Guard empty input immediately so we can safely inspect merged[-1] later.
        if not intervals:
            return []
    
        # Phase 1: Sort [start, end] pairs lexicographically (by start ascending, then end ascending).
        sorted_intervals = sorted(intervals)
    
        # merged: list of disjoint [start, end] intervals ordered by start time, e.g. [[2, 9], [12, 16]].
        merged: List[List[int]] = []
    
        # Phase 2: Sweep left to right, extending the active block or starting a new one.
        for start, end in sorted_intervals:
            # Strict `>` means a real gap exists (touching endpoints like [0, 6] and [6, 11] have 6 <= 6,
            # so they go to the `else` branch and merge). Append a fresh list to avoid mutating input.
            if not merged or start > merged[-1][1]:
                merged.append([start, end])
            else:
                # Use max() because a nested interval like [5, 7] inside [2, 9] must not shrink 9 to 7.
                merged[-1][1] = max(merged[-1][1], end)
    
        return merged
    
  5. Trace the examples step by step

    Let's trace Example 1 ([[12, 16], [2, 5], [4, 9], [20, 25], [5, 7]]) and Example 2 ([[6, 11], [0, 6], [14, 19]]):

    Example 1: sorted_intervals = [[2, 5], [4, 9], [5, 7], [12, 16], [20, 25]]
      read [2, 5]   -> merged is empty           -> append [2, 5]     | merged = [[2, 5]]
      read [4, 9]   -> 4 <= 5 (overlap!)         -> max(5, 9) = 9     | merged = [[2, 9]]
      read [5, 7]   -> 5 <= 9 (nested inside!)   -> max(9, 7) = 9     | merged = [[2, 9]]
      read [12, 16] -> 12 > 9 (gap!)             -> append [12, 16]   | merged = [[2, 9], [12, 16]]
      read [20, 25] -> 20 > 16 (gap!)            -> append [20, 25]   | merged = [[2, 9], [12, 16], [20, 25]]
    
    Example 2: sorted_intervals = [[0, 6], [6, 11], [14, 19]]
      read [0, 6]   -> merged is empty           -> append [0, 6]     | merged = [[0, 6]]
      read [6, 11]  -> 6 <= 6 (shared boundary!) -> max(6, 11) = 11   | merged = [[0, 11]]
      read [14, 19] -> 14 > 11 (gap!)            -> append [14, 19]   | merged = [[0, 11], [14, 19]]
    
  6. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def merge_intervals(intervals: List[List[int]]) -> List[List[int]]:
        # Guard empty input immediately so we can safely inspect merged[-1] later.
        if not intervals:
            return []
    
        # Phase 1: Sort [start, end] pairs lexicographically (by start ascending, then end ascending).
        sorted_intervals = sorted(intervals)
    
        # merged: list of disjoint [start, end] intervals ordered by start time, e.g. [[2, 9], [12, 16]].
        merged: List[List[int]] = []
    
        # Phase 2: Sweep left to right, extending the active block or starting a new one.
        for start, end in sorted_intervals:
            # Strict `>` means a real gap exists (touching endpoints like [0, 6] and [6, 11] have 6 <= 6,
            # so they go to the `else` branch and merge). Append a fresh list to avoid mutating input.
            if not merged or start > merged[-1][1]:
                merged.append([start, end])
            else:
                # Use max() because a nested interval like [5, 7] inside [2, 9] must not shrink 9 to 7.
                merged[-1][1] = max(merged[-1][1], end)
    
        return merged
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine consolidating busy blocks on a person's calendar when meeting sticky notes are tossed onto your desk in random order. If you leave them scrambled, you have to compare every note against every other note to see which meetings run together. Instead, if you line the sticky notes up left-to-right by their start times, you can slide one finger across the timeline: whenever the next meeting starts before (or right at the moment) your current busy block ends, you stretch the current block to cover both; whenever there is a gap of free time, you seal the current block and start a fresh one.

Why does the naive approach fall short? Without sorting, two overlapping intervals can sit anywhere in the list, and merging two intervals into a wider one can suddenly make it overlap a third interval you checked earlier. Repeatedly scanning all pairs until nothing merges can take O(n^3) time in the worst case, which is far too slow for 10,000 intervals.

Here each [start, end] is a closed interval (an interval that includes both endpoints start and end, so [0, 6] and [6, 11] touch at 6 and merge). Sorting [start, end] lists in lexicographical order (comparing the first element start, and breaking ties with end) lets a single left-to-right pass finish the job. Let's trace Example 1 ([[12, 16], [2, 5], [4, 9], [20, 25], [5, 7]]):

Step 1 - Sort by start: [[2, 5], [4, 9], [5, 7], [12, 16], [20, 25]]

Step 2 - Sweep left to right:
  [2, 5]   -> start first block:                merged = [[2, 5]]
  [4, 9]   -> 4 <= 5 (overlaps!), end=max(5,9): merged = [[2, 9]]
  [5, 7]   -> 5 <= 9 (nested!), end=max(9,7):   merged = [[2, 9]]
  [12, 16] -> 12 > 9 (gap!), start new block:   merged = [[2, 9], [12, 16]]
  [20, 25] -> 20 > 16 (gap!), start new block:  merged = [[2, 9], [12, 16], [20, 25]]

Complexity

Let n = len(intervals).

  • Time: O(n log n). Sorting the n intervals takes O(n log n) comparisons, and the single for loop afterward visits each of the n intervals once, doing O(1) boundary checks and list updates per step.
  • Space: O(n). sorted(intervals) creates a sorted outer list of length n, and merged stores up to n two-element lists when no intervals overlap.

Edge cases

  • Empty list []: Handled right away and returns [].
  • Single interval [[5, 8]]: Appended as a new [5, 8] list and returned unchanged.
  • Touching boundary [[0, 6], [6, 11]]: Because 6 > 6 is False (6 <= 6), the shared endpoint 6 merges them into [[0, 11]].
  • Adjacent integers [[2, 3], [4, 5]]: Because 4 > 3, the uncovered open gap (3, 4) keeps them separate as [[2, 3], [4, 5]].
  • Nested interval [[2, 9], [5, 7]]: max(9, 7) preserves 9, absorbing [5, 7] into [[2, 9]] without shrinking the end.
  • Duplicate intervals [[3, 7], [3, 7]]: Collapse cleanly into [[3, 7]].

Common mistakes

  • Using < instead of <= for overlap (or >= instead of > for a gap): Treating start == merged[-1][1] as non-overlapping leaves [0, 6] and [6, 11] separate instead of merging them into [0, 11].
  • Assigning merged[-1][1] = end without max(...): If [2, 9] is followed by [5, 7], blindly overwriting the end shrinks [2, 9] into [2, 7].
  • Comparing against the previous input interval sorted_intervals[i - 1] instead of merged[-1]: On [[1, 12], [2, 4], [6, 8]], [6, 8] does not overlap [2, 4], yet it still lies inside the active merged block [1, 12].
  • Mutating the caller's inner lists by appending interval directly: Writing merged.append(interval) aliases the caller's [start, end] list, so modifying merged[-1][1] silently alters the input data. Appending [start, end] creates an independent 2-element copy.
  • Sorting by end coordinate instead of start coordinate: Sorting by end can place a wide interval like [1, 12] after [9, 10], breaking the left-to-right invariant unless you scan backward from right to left.

Alternative approaches

  • Coordinate event sweep: A sweep-line algorithm turns each [start, end] into two point events — (start, -1) for opening and (end, +1) for closing (sorting -1 before +1 at ties so [0, 6] and [6, 11] stay connected) — then sorts all 2n events and tracks how many intervals are currently open. Whenever the active count rises from 0 to 1 an interval begins, and whenever it drops back to 0 an interval ends; this also runs in O(n log n) time.
  • Coordinate difference array: A difference array stores only the net change in coverage at each integer coordinate (diff[start] += 1, diff[end] -= 1 over unit segments [x, x + 1)), then computes running prefix sums from 0 to max_end (<= 10^6) in O(n + max_end) time without comparison sorting. That only helps when coordinates are small non-negative integers and n is very large.

Follow-up questions

  • What are the asymptotic runtime and memory costs of this solution, and how can extra memory be reduced if modifying the input list is allowed? Our solution uses O(n log n) time and O(n) space because it leaves the input untouched and builds a fresh output list. If the caller permits modifying intervals in place, you can call intervals.sort(), maintain a write index of the last merged slot inside intervals, merge overlapping entries directly into intervals[write], and slice off the tail with del intervals[write + 1:]. That eliminates the separate output list, reducing auxiliary memory beyond the sort itself to O(1) (note that Python's Timsort — Python's built-in hybrid merge/insertion sort — still uses up to O(n) temporary scratch pointers in the worst case, whereas an in-place heapsort uses O(1) extra space).
  • Suppose you already have a sorted list of disjoint intervals and want to add one new interval—how would you adapt the approach? Because an already merged list is sorted and mutually disjoint, no sorting is needed and a single O(n) scan suffices: copy all intervals ending strictly before new_start (end < new_start), absorb every overlapping interval (start <= new_end) into [min(new_start, start), max(new_end, end)], append that merged interval, and copy the remaining intervals (start > new_end). You can find the first and last overlapping positions in O(log n) time using binary search (repeatedly halving the sorted search range), though splicing into a flat Python list still shifts up to O(n) elements unless intervals are stored in a balanced search tree.
  • How does the runtime change when the input intervals arrive pre-ordered by their starting coordinate? Skipping sorted(intervals) drops the total runtime from O(n log n) to O(n), since only the single linear merge pass remains. Interestingly, even if you still call sorted(intervals) in Python, Timsort automatically detects pre-sorted runs in a single scan and finishes in O(n) comparisons!

Follow-up questions

Similar questions

More Apple interview questions

All 177 Apple questions →