Merge Overlapping Intervals

Medium · Coding & Algorithms · Software Engineer · Online Assessment

Problem Statement

Given a collection of closed integer intervals intervals, where each element intervals[i] = [start_i, end_i] spans every real number x satisfying start_i <= x <= end_i, combine every group of overlapping intervals into a single interval and return the resulting disjoint intervals ordered by increasing start coordinate.

The input list arrives in arbitrary order and may include duplicate intervals, intervals completely contained inside wider intervals, zero-length point intervals (start_i == end_i), and negative coordinates.

Two closed intervals [a, b] and [c, d] overlap whenever max(a, c) <= min(b, d)—that is, whenever at least one number belongs to both. In particular, intervals that meet at a single shared endpoint (such as [1, 6] and [6, 11], which both include 6) must be combined into [1, 11], whereas intervals separated by an open gap (such as [2, 9] and [10, 14], which leave numbers like 9.5 uncovered) remain separate.

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

Examples

Example 1

Input: intervals = [[10, 14], [2, 5], [4, 9], [20, 22]]
Output: [[2, 9], [10, 14], [20, 22]]

Sorting by start yields [2, 5], [4, 9], [10, 14], [20, 22]. [2, 5] and [4, 9] share [4, 5] and combine into [2, 9], while [10, 14] (10 > 9) and [20, 22] (20 > 14) have no overlap with earlier spans.

Example 2

Input: intervals = [[6, 11], [-5, -1], [1, 6], [2, 4]]
Output: [[-5, -1], [1, 11]]

Sorting produces [-5, -1], [1, 6], [2, 4], [6, 11]. [-5, -1] stays isolated; [2, 4] lies completely inside [1, 6], and [6, 11] shares boundary point 6 with [1, 6], extending that span to [1, 11].

Constraints

  • 0 <= len(intervals) <= 10^5
  • len(intervals[i]) == 2
  • -10^9 <= start_i <= end_i <= 10^9
  • Return [] when intervals is empty, and do not mutate the caller's input lists.

Step-by-step walkthrough

  1. Understand closed intervals and the overlap condition

    Every input pair [start, end] represents a closed interval (all real numbers x satisfying start <= x <= end, inclusive of both endpoints). Two closed intervals [a, b] and [c, d] overlap whenever at least one number belongs to both—equivalently, max(a, c) <= min(b, d):

    Number line:  1   2   4   5   6   9  10  11
                  .   [=======]   .   .   .   .   [2, 5] and [4, 9] share [4, 5]   -> merge to [2, 9]
                  .   .   [===========]   .   .
    
                  [===========]   .   .   .   .   [1, 6] and [6, 11] share point 6 -> merge to [1, 11]
                  .   .   .   [===============]
    
                  .   [===============]   .   .   [2, 9] and [10, 14] share nothing -> stay separate
                  .   .   .   .   .   .   [====   (values like 9.5 lie uncovered between 9 and 10!)
    

    Pay close attention to the boundary rule: [1, 6] and [6, 11] share 6 and merge, whereas [2, 9] and [10, 14] share zero points and stay separate.

  2. Why pairwise brute-force merging is too slow

    A naive loop searches all pairs (i, j) in the list, merges the first overlapping pair into [min(a, c), max(b, d)], and repeats from scratch until no pair overlaps:

    • Scanning for a single overlapping pair can check O(n^2) pairs.
    • Each merge removes 1 interval, so up to n - 1 merges can occur.

    In the worst case that costs O(n^3) operations—far too slow for n = 10^5.

  3. Key insight: sort by start coordinate first

    Why did the naive loop have to re-check distant pairs? Because an early-starting interval could sit anywhere near the end of an unsorted list. Sorting all intervals by start in ascending order unlocks a single-pass invariant:

    Active span at merged[-1]:            [=========]
                                                    ^ last_end
    
    Case A (start <= last_end):               [=======]      -> shares 'start', so absorb into merged[-1]!
    Case B (start >  last_end):                     [=====]  -> open gap! Every later span starts >= start > last_end,
                                                                so merged[-1] can never grow again!
    

    Because every remaining interval in sorted order has future_start >= start, as soon as start > last_end, no later interval can ever reach back across that gap to touch merged[-1]. Consequently, each interval only needs to be compared against merged[-1].

  4. Code the single-pass sweep

    After handling if not intervals: return [] and sorting into sorted_intervals, initialize merged with a fresh copy [first_start, first_end] of the earliest interval and sweep through the rest:

    1. Shared boundary points (<=, not <): When start == last_end, both closed intervals contain that point, so start <= last_end merges them.
    2. Nested intervals (max(last_end, end)): When [2, 4] lies inside [1, 6], blindly assigning end (4) would shrink [1, 6] to [1, 4] and miss the later [6, 11] merge! Taking max(last_end, end) preserves 6.
    3. Protect caller lists: Always allocate a fresh [start, end] two-element list instead of appending references to the caller's inner lists.
    sorted_intervals = sorted(intervals)
    first_start, first_end = sorted_intervals[0]
    merged: List[List[int]] = [[first_start, first_end]]
    
    for start, end in sorted_intervals[1:]:
        last_interval = merged[-1]
        last_end = last_interval[1]
        if start <= last_end:
            last_interval[1] = max(last_end, end)
        else:
            merged.append([start, end])
    
  5. Walk through Example 1 and Example 2 step by step

    Example 1: intervals = [[10, 14], [2, 5], [4, 9], [20, 22]]

    Sorted: [2, 5], [4, 9], [10, 14], [20, 22]
    
    Seed:         merged = [[2, 5]]
    Read [4, 9]:    4 <= 5  (overlap!) -> end = max(5, 9) = 9  -> merged = [[2, 9]]
    Read [10, 14]: 10 >  9  (gap!)     -> start new span       -> merged = [[2, 9], [10, 14]]
    Read [20, 22]: 20 > 14  (gap!)     -> start new span       -> merged = [[2, 9], [10, 14], [20, 22]]
    

    Example 2: intervals = [[6, 11], [-5, -1], [1, 6], [2, 4]]

    Sorted: [-5, -1], [1, 6], [2, 4], [6, 11]
    
    Seed:         merged = [[-5, -1]]
    Read [1, 6]:    1 > -1  (gap!)     -> start new span       -> merged = [[-5, -1], [1, 6]]
    Read [2, 4]:    2 <= 6  (nested!)  -> end = max(6, 4) = 6  -> merged = [[-5, -1], [1, 6]]
    Read [6, 11]:   6 <= 6  (touch!)   -> end = max(6, 11)= 11 -> merged = [[-5, -1], [1, 11]]
    
  6. 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 intervals by start point (and by end point on ties).
        # Built-in sorted() compares [start, end] pairs element-by-element without mutating input.
        sorted_intervals = sorted(intervals)
    
        # merged: list of non-overlapping [start, end] intervals sorted by start;
        # merged[-1] is the active group currently growing.
        first_start, first_end = sorted_intervals[0]
        merged: List[List[int]] = [[first_start, first_end]]
    
        # Phase 2: Sweep left to right; once sorted, an interval can only overlap merged[-1].
        for start, end in sorted_intervals[1:]:
            last_interval = merged[-1]
            last_end = last_interval[1]
    
            # Closed intervals include both endpoints, so '<=' merges touching endpoints
            # like [1, 6] and [6, 11] (which share point 6).
            if start <= last_end:
                # Use max() so a nested interval like [2, 3] inside [1, 10] never shrinks last_end.
                last_interval[1] = max(last_end, end)
            else:
                # Because start > last_end and all later intervals start >= start,
                # last_interval can never merge again. Append a fresh copy to protect caller data.
                merged.append([start, end])
    
        return merged
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture tidying up reservation blocks on a shared room schedule when requests arrived out of chronological order. While paper slips sit shuffled in a pile, combining two overlapping bookings can create a wider block that suddenly bridges into another slip buried elsewhere in the stack, forcing repeated passes. Arranging every slip from earliest start time to latest start time reduces the job to one clean left-to-right sweep: the next booking either overlaps the single active block at the tail of your output, or begins strictly past its end—and once an open gap appears, no later booking can ever reach back across that gap.

Without sorting first, comparing only adjacent input items misses overlaps separated by unrelated entries (such as [2, 5] and [4, 9] sitting after [10, 14]). Repeatedly scanning all O(n^2) pairs and fusing one pair per pass works on tiny lists, but up to n - 1 merges drive worst-case runtime to O(n^3), timing out completely near n = 10^5. Sorting once in O(n log n) time makes the merge sweep itself strictly O(n).

Let's trace Example 2, [[6, 11], [-5, -1], [1, 6], [2, 4]]:

  1. Sort by start: [[-5, -1], [1, 6], [2, 4], [6, 11]], and seed merged = [[-5, -1]].
  2. Visit [1, 6]: Start 1 exceeds active end -1, so [-5, -1] is permanently finished and we append [1, 6] (merged = [[-5, -1], [1, 6]]).
  3. Visit [2, 4]: Since 2 <= 6, it overlaps [1, 6]; setting the end to max(6, 4) = 6 prevents the nested [2, 4] from shrinking [1, 6].
  4. Visit [6, 11]: Because closed intervals contain both endpoints, 6 <= 6 means point 6 belongs to both [1, 6] and [6, 11], extending the active end to max(6, 11) = 11 and returning [[-5, -1], [1, 11]].

Complexity

  • Time: O(n log n), where n = len(intervals). Sorting n two-element lists with Python's Timsort (a hybrid merge-and-insertion sort) takes O(n log n) comparisons, and the single linear sweep afterward visits each interval once in O(1) time per step.
  • Space: O(n). sorted_intervals holds n list references (plus Timsort's scratch buffer of up to n / 2 references), and merged stores up to n two-element output lists when every interval is disjoint.

Edge cases

  • Empty input ([]): Returns [] immediately before indexing sorted_intervals[0].
  • Single or zero-length point interval ([[5, 5]]): Returns a fresh copy [[5, 5]] without entering the loop.
  • Shared single-point boundary ([[1, 6], [6, 11]]): Merges into [[1, 11]] because both closed intervals include 6.
  • Consecutive integers ([[2, 9], [10, 14]]): Kept separate as [[2, 9], [10, 14]] because real numbers strictly between 9 and 10 belong to neither interval.
  • Nested intervals ([[1, 6], [2, 4], [6, 11]]): max(last_end, end) retains 6 across [2, 4] so [6, 11] still merges into [[1, 11]].
  • Duplicates and extreme coordinates (±10^9): Identical spans sort side-by-side and collapse into one, and arbitrary-precision Python ints avoid overflow.

Common mistakes

  • Testing start < last_end instead of start <= last_end: Fails to merge closed intervals that touch at one boundary point (such as [1, 6] and [6, 11] in Example 2).
  • Assigning last_interval[1] = end without max: Shrinks the active block whenever a shorter interval sits nested inside a wider one, breaking downstream merges.
  • Testing start <= last_end + 1: Treats continuous closed intervals like discrete integer ranges; [2, 9] and [10, 14] must remain separate.
  • Sweeping without sorting first: Only merges overlapping intervals that happen to sit adjacent in the raw input.
  • Mutating the caller's inner lists: Appending sorted_intervals[i] directly and editing last_interval[1] mutates the caller's input in place.

Alternative approaches

  • Coordinate sweep-line algorithm: A sweep-line algorithm (converting interval endpoints into sorted coordinate events processed left to right) emits (start, -1) and (end, +1) per interval, ordering -1 before +1 on coordinate ties so touching endpoints fuse before closing. Tracking active coverage depth and recording spans where depth transitions 0 -> 1 and 1 -> 0 also runs in O(n log n) time, at the cost of allocating 2n event tuples.

Follow-up questions

  • What data structure would you maintain if new intervals arrived dynamically one at a time and callers queried the merged state online? Maintain the disjoint merged intervals inside a balanced binary search tree (a self-balancing ordered tree such as an AVL or red-black tree, or sortedcontainers.SortedDict in Python) keyed by start. When [s, e] arrives, look up the predecessor interval with largest start <= s; if its end >= s, remove it and set s = pred_start, e = max(e, pred_end). Then repeatedly remove every successor interval whose start <= e, updating e = max(e, succ_end), and insert the consolidated [s, e]. Because each inserted interval can be deleted at most once over the entire stream, the amortized time (average cost per operation across any sequence of updates) is O(log n) per insertion.
  • If mutating the input array is allowed, how can you compact the merged result in place using O(1) extra memory beyond the sort? Use an in-place algorithm (reusing the input list's own slots rather than allocating merged). Guard if not intervals: return intervals, sort intervals.sort(), and keep a write cursor write = 0 marking the active merged slot. For each read in 1 .. len(intervals) - 1, if intervals[read][0] <= intervals[write][1], set intervals[write][1] = max(intervals[write][1], intervals[read][1]); otherwise advance write += 1 and set intervals[write] = intervals[read], finishing with del intervals[write + 1:] in O(1) extra index variables.
  • How would your sort order and boundary checks change if each endpoint could independently be inclusive (closed) or exclusive (open)? Represent each interval as (start, start_closed, end, end_closed) and sort by (start, not start_closed) so inclusive starts [p, ... precede exclusive starts (p, ... at tied coordinate p (preventing [1, 3], (3, 10], [3, 4] from prematurely splitting at 3). Whenever start < last_end the spans overlap; at start == last_end, they share point p iff last_end_closed and start_closed (or form a gapless union iff last_end_closed or start_closed, such as [1, 3) union [3, 5]). When extending the right boundary, adopt (end, end_closed) if end > last_end, or set last_end_closed = last_end_closed or end_closed if end == last_end.

Follow-up questions

Similar questions

More Micro1 interview questions

All 2 Micro1 questions →