Consolidate Overlapping Intervals

Medium · Coding & Algorithms · Applied Scientist · Technical Screen

Problem Statement

You receive a list intervals where each element is a two-integer list [start, end] denoting a closed continuous range [start, end]. Two ranges [a, b] and [c, d] intersect whenever they contain at least one common point—including a shared boundary endpoint (for example, [3, 7] and [7, 11] intersect at 7 and coalesce into [3, 11]).

Implement:

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

Combine all intersecting ranges (including chains of ranges and completely nested sub-ranges) and return a new list of pairwise disjoint [start, end] intervals in ascending order of start.

Examples

Example 1

Input: intervals = [[12, 16], [2, 5], [4, 9], [20, 24], [6, 8]]
Output: [[2, 9], [12, 16], [20, 24]]

Sorting by start coordinate gives [[2, 5], [4, 9], [6, 8], [12, 16], [20, 24]]. [2, 5] and [4, 9] overlap on [4, 5] to form [2, 9], which completely absorbs [6, 8]. [12, 16] and [20, 24] share no points with anything else and remain distinct.

Example 2

Input: intervals = [[3, 7], [7, 11]]
Output: [[3, 11]]

Because endpoints are inclusive, [3, 7] and [7, 11] touch at 7 and coalesce into [3, 11].

Constraints

  • 1 <= len(intervals) <= 10,000
  • 0 <= start < end <= 10^9
  • intervals may be given in arbitrary order.

Step-by-step walkthrough

  1. Understand when two time ranges merge

    We receive up to 10,000 closed intervals [start, end] with 0 <= start < end <= 10^9, possibly in arbitrary order. Two intervals merge whenever they share at least one point—including just an endpoint—and merging chains transitively across multiple intervals:

    Touching endpoints merge:    [3------7]
                                         [7----11]    -->  [3----------11]
    
    Integer gap stays separate:  [1--2]  [3--4]       -->  [1--2], [3--4]  (no shared point)
    
    Nested interval absorbed:    [2------------9]
                                       [6--8]         -->  [2------------9]
    

    Our output must be a new list of merged [start, end] intervals with no remaining overlaps.

  2. Why checking every pair is too slow

    If the intervals are in random order, [1, 4] at the beginning of the list might connect to [7, 9] near the end only because [4, 7] appears somewhere in the middle. Checking all pairs of intervals and grouping connected components (for example with union-find) inspects n * (n - 1) / 2 pairs—roughly 50,000,000 comparisons when n = 10,000.

    That quadratic work only happens because the intervals are scrambled. On an ordered timeline, overlaps can only happen right next to each other.

  3. Key idea: sort by start time so overlaps only touch the last range

    Suppose we sort all intervals by their start coordinate from smallest to largest. As we scan left to right, we maintain merged, our list of finished and active ranges. Look at the very last range in merged, [last_start, last_end], and the next incoming interval [start, end]. Because we sorted by start time, we already know last_start <= start. Only two cases are possible:

    Case 1: start <= last_end (overlap or touch)
      last_range:  [last_start -------- last_end]
      incoming:                 [start ----------- end]
      updated:     [last_start ------------------- max(last_end, end)]
    
    Case 2: start > last_end (strict gap)
      last_range:  [last_start ---- last_end]
      incoming:                               [start ---- end]
      action:      last_range is sealed forever; append [start, end] as the new active range!
    

    Why can we seal last_range forever in Case 2? Because every future interval in sorted_intervals starts at or after start, which is already strictly greater than last_end—so no later interval can ever reach back across the gap!

  4. Sort and sweep through the intervals

    In Python, comparing two [start, end] lists compares index 0 (start) first and index 1 (end) on ties, so sorted(intervals) puts everything in ascending start order without mutating the caller's list.

    During the single left-to-right pass, pay close attention to three details: 1. Copy [start, end] when appending so extending last_range[1] later never mutates the caller's input lists. 2. Use <= instead of < so touching endpoints like [3, 7] and [7, 11] merge. 3. Use max(last_end, end) so a completely contained interval like [2, 3] inside [1, 5] does not shrink last_end from 5 down to 3.

    def merge_intervals(intervals: List[List[int]]) -> List[List[int]]:
        # Two-element lists compare item by item, so sorted() orders by start time
        # (and by end time on ties) while leaving the caller's list untouched.
        sorted_intervals = sorted(intervals)
    
        # merged: non-overlapping [start, end] ranges in ascending order of start time.
        merged: List[List[int]] = []
    
        for start, end in sorted_intervals:
            if not merged:
                # Copy [start, end] so mutating merged[-1] later never mutates input sublists.
                merged.append([start, end])
                continue
    
            last_range = merged[-1]
            last_end = last_range[1]
    
            # Use <= (not <) because closed intervals that share an endpoint (like [3, 7] and [7, 11]) merge.
            if start <= last_end:
                # Take max(last_end, end) so a shorter nested range like [2, 3] inside [1, 5] never shrinks last_end.
                last_range[1] = max(last_end, end)
            else:
                # Strict gap (start > last_end): every remaining interval also starts >= start, so last_range is final.
                merged.append([start, end])
    
        return merged
    
  5. Trace Example 1 and Example 2

    Let us trace Example 1 ([[12, 16], [2, 5], [4, 9], [20, 24], [6, 8]], which sorts to [[2, 5], [4, 9], [6, 8], [12, 16], [20, 24]]):

    Incoming    last_range   Check (start <= last_end?)   Action                    merged
    ------------------------------------------------------------------------------------------------------------
    [2, 5]      none         first interval               append [2, 5]             [[2, 5]]
    [4, 9]      [2, 5]       4 <= 5 (True)                end = max(5, 9) = 9       [[2, 9]]
    [6, 8]      [2, 9]       6 <= 9 (True, nested!)       end = max(9, 8) = 9       [[2, 9]]
    [12, 16]    [2, 9]       12 <= 9 (False, gap!)        append [12, 16]           [[2, 9], [12, 16]]
    [20, 24]    [12, 16]     20 <= 16 (False, gap!)       append [20, 24]           [[2, 9], [12, 16], [20, 24]]
    

    And Example 2 ([[3, 7], [7, 11]]): - [3, 7] starts merged = [[3, 7]]. - [7, 11] checks 7 <= 7 (True), updating last_range[1] = max(7, 11) = 11 to produce [[3, 11]].

  6. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def merge_intervals(intervals: List[List[int]]) -> List[List[int]]:
        # Two-element lists compare item by item, so sorted() orders by start time
        # (and by end time on ties) while leaving the caller's list untouched.
        sorted_intervals = sorted(intervals)
    
        # merged: non-overlapping [start, end] ranges in ascending order of start time.
        merged: List[List[int]] = []
    
        for start, end in sorted_intervals:
            if not merged:
                # Copy [start, end] so mutating merged[-1] later never mutates input sublists.
                merged.append([start, end])
                continue
    
            last_range = merged[-1]
            last_end = last_range[1]
    
            # Use <= (not <) because closed intervals that share an endpoint (like [3, 7] and [7, 11]) merge.
            if start <= last_end:
                # Take max(last_end, end) so a shorter nested range like [2, 3] inside [1, 5] never shrinks last_end.
                last_range[1] = max(last_end, end)
            else:
                # Strict gap (start > last_end): every remaining interval also starts >= start, so last_range is final.
                merged.append([start, end])
    
        return merged
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine consolidating busy blocks on a daily calendar from a pile of shuffled meeting sticky notes. If the notes sit in random order on your desk, checking whether two meetings connect (possibly through a third bridge meeting!) forces you to compare notes against everything else. Once you line the notes up from earliest start time to latest start time, you can simply slide your finger down the page: keep extending your current busy block whenever the next meeting starts before (or right as) the current block ends, and start a fresh block only when you hit an open gap.

Each [start, end] here is a closed interval (a range that includes both its start and end endpoints, so [3, 7] and [7, 11] share point 7), and overlap is transitive (if interval A overlaps B and B overlaps C, all three merge into one continuous range). A naive approach tests every pair of intervals and groups connected components, taking O(n^2) time—around 50 million pair checks for 10,000 intervals.

Sorting by start reduces the entire merge to one linear scan because any interval that connects to our current active range [last_start, last_end] must have start <= last_end. Here is how [[12, 16], [2, 5], [4, 9], [6, 8]] works step by step: 1. Sort by start: [[2, 5], [4, 9], [6, 8], [12, 16]]. 2. Read [2, 5]: merged is empty, so start merged = [[2, 5]]. 3. Read [4, 9]: Since 4 <= 5, it overlaps [2, 5]; extend last_end to max(5, 9) = 9, giving merged = [[2, 9]]. 4. Read [6, 8]: Since 6 <= 9, it lies inside [2, 9]; max(9, 8) = 9 leaves merged = [[2, 9]]. 5. Read [12, 16]: Since 12 > 9, there is a gap after 9 that no later interval can cross; append [12, 16] to finish with [[2, 9], [12, 16]].

Complexity

Let n be the number of intervals in 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 loop inspects each interval once in O(1) time (O(n) total), so sorting dominates.
  • Space: O(n). sorted(intervals) creates an n-element shallow list copy, and merged stores up to n output intervals when no intervals overlap.

Edge cases

  • Single interval ([[5, 7]]): Appended once and returned as [[5, 7]].
  • Touching endpoints ([[3, 7], [7, 11]]): Merged into [[3, 11]] because 7 <= 7 satisfies start <= last_end.
  • Adjacent integers with no shared point ([[1, 2], [3, 4]]): Kept separate as [[1, 2], [3, 4]] because 3 > 2 (unlike discrete integer-set problems, [1, 2] and [3, 4] leave the open gap (2, 3) uncovered).
  • Completely nested intervals ([[2, 15], [5, 9]]): max(15, 9) keeps last_end = 15 rather than shrinking it to 9.
  • Identical intervals or tied start times ([[1, 3], [1, 7], [1, 3]]): Merged cleanly into [[1, 7]].
  • Large coordinates (0 to 10^9): We never allocate an array indexed by timestamp (which would require 10^9 slots and run out of memory); we only compare endpoint integers directly.

Common mistakes

  • Writing start < last_end instead of start <= last_end: Fails Example 2 ([[3, 7], [7, 11]]) by leaving touching intervals unmerged.
  • Overwriting last_range[1] = end instead of max(last_end, end): On [[1, 5], [2, 3], [4, 8]], [2, 3] would shrink the active range to [1, 3], causing [4, 8] to falsely split off as a separate range!
  • Sorting by end time instead of start time: After sorting by end ([[2, 3], [4, 5], [1, 6]]), [1, 6] arrives last and overlaps both earlier ranges in merged, breaking the single-range check.
  • Appending the original sublist interval without copying [start, end]: Mutating last_range[1] in place then silently corrupts the caller's input list!

Alternative approaches

  • Boundary event sweep: A sweep-line algorithm converts each interval into a +1 start event and a -1 end event, sorts all 2n events along the timeline (ordering +1 before -1 at equal coordinates so touching ranges connect), and emits a merged interval whenever the active counter rises from 0 and drops back to 0. It also runs in O(n log n) time and generalizes naturally when you need overlap depth (such as minimum meeting rooms).

Follow-up questions

  • What changes in your implementation and runtime if the caller guarantees intervals arrives pre-sorted by start coordinate? Simply remove the sorted(intervals) step and run the linear merge loop directly over intervals, dropping the time complexity from O(n log n) to O(n) and avoiding the O(n) sorted copy. (Interestingly, Python's built-in Timsort—a hybrid sorting algorithm designed to exploit existing order—already detects a pre-sorted run in O(n) comparisons, though skipping sorted() still saves allocating the intermediate list and makes the O(n) guarantee explicit.)
  • Can you reduce the auxiliary memory usage beyond O(n) if mutating the input list is allowed? Our solution runs in O(n log n) time and O(n) space. If the caller permits mutating intervals, we can turn the merge pass into an in-place algorithm (one that reuses the input array instead of allocating a separate output list): call intervals.sort(), maintain a write index starting at 0, merge overlapping intervals into intervals[write], advance write += 1 on gaps, and slice off the tail with del intervals[write + 1:]. That eliminates the separate output allocation, leaving only the sorting algorithm's internal scratch space (O(n) worst-case pointers in Python's Timsort, or O(1) auxiliary space in C++ heapsort).
  • How should the function behave if malformed ranges with start > end can appear in the input? Clarify the expected contract with the interviewer before coding, because running the sweep blindly on [5, 1] treats 5 as the start and 1 as the end and corrupts nearby merges. In most APIs and backend services, the safest choice is strict fail-fast validation: run an O(n) check at the top of merge_intervals and raise a descriptive ValueError whenever start > end (or start >= end if zero-length intervals are disallowed). If the upstream data source is known to occasionally swap timestamps, normalize each pair to [min(a, b), max(a, b)] before sorting; in an analytics pipeline, filter invalid rows out and increment an error metric.

Follow-up questions

Similar questions

More Amazon interview questions

All 653 Amazon questions →