Coalesce Overlapping Closed Intervals

Easy · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Given an arbitrarily ordered list of closed intervals [start, end] with integer endpoints, merge every group of intersecting intervals into a single [min_start, max_end] interval and return the resulting non-overlapping intervals ordered by ascending start.

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

Follow these exact rules:

  • Every [start, end] satisfies start <= end and represents the closed continuous interval containing start, end, and all real numbers between them.
  • Two intervals intersect whenever they share at least one real number. Intervals that meet at a single endpoint—such as [2, 6] and [6, 9], or [8, 8] and [8, 11]—share that boundary point and must be merged.
  • Intervals separated by an uncovered real open gap—such as [0, 5] and [6, 8]—share zero points (for example, 5.5 lies in neither interval) and must remain separate, even though no integer sits strictly between 5 and 6.
  • Merging is transitive: whenever intervals are connected by a chain of pairwise overlaps (I_1 intersects I_2 and I_2 intersects I_3), collapse the entire chain into one interval [smallest_start, largest_end] covering the exact same set of real points.
  • Duplicate intervals, single-point intervals (start == end), and intervals strictly nested inside wider intervals may appear in the input.
  • Return the merged disjoint intervals sorted in strictly increasing order of start, without mutating the caller's input list or sublists.

Examples

Example 1

Input: intervals = [[10, 14], [2, 8], [4, 6], [12, 18]]
Output: [[2, 8], [10, 18]]

[4, 6] lies completely inside [2, 8], leaving [2, 8]. [10, 14] and [12, 18] overlap across [12, 14] and coalesce into [10, 18].

Example 2

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

[0, 5] and [6, 8] stay separate because real numbers strictly between 5 and 6 are uncovered. [6, 8], [8, 8], and [8, 11] all share point 8 and combine into [6, 11].

Example 3

Input: intervals = [[-8, -3], [-4, 1], [-8, -3], [3, 5]]
Output: [[-8, 1], [3, 5]]

Both copies of [-8, -3] intersect [-4, 1] and collapse into [-8, 1], while [3, 5] has no overlap and remains separate.

Constraints

  • 1 <= len(intervals) <= 10^5
  • Each element of intervals is a two-integer list [start, end] with -10^9 <= start <= end <= 10^9.

Step-by-step walkthrough

  1. Understand the problem and the overlap rule

    We receive an unsorted list of closed intervals [start, end] with start <= end, where each interval covers start, end, and every real number on the continuous number line between them. We need to collapse every chain of intersecting intervals into a single [smallest_start, largest_end] range and return the resulting disjoint ranges sorted by start.

    Pay close attention to three boundary behaviors on the real line:

    1. Touching endpoints OVERLAP (they share point 6):
       [2, 6]:   2===========6
       [6, 9]:               6========9
       merged:   2====================9   -> [2, 9]
    
    2. Consecutive integers DO NOT overlap (real points like 5.5 are uncovered):
       [0, 5]:   0=============5
       [6, 8]:                     6=====8
       merged:   0=============5   6=====8  -> [[0, 5], [6, 8]]
    
    3. Overlap chains merge transitively ([3, 7] bridges [1, 4] and [6, 10]):
       [1, 4]:   1=======4
       [3, 7]:        3==========7
       [6, 10]:               6==========10
       merged:   1=======================10 -> [1, 10]
    
  2. Why checking every pair is too slow

    A naive brute-force approach treats intervals as vertices in a graph, compares every pair of intervals to test whether they share a point (max(a, c) <= min(b, d)), and collapses each connected group into [min_start, max_end].

    With n up to 100,000, testing all n * (n - 1) / 2 pairs performs roughly 5 * 10^9 comparisons (O(n^2) time), which exceeds the time limit. The only reason all-pairs checks were needed is that intersecting intervals sit scattered throughout the input.

  3. Key idea: sort by start, then sweep left to right

    If we first sort the intervals in ascending order of start (breaking ties by end), every connected chain of overlapping intervals becomes a contiguous block in the sorted list. We can then sweep from left to right while maintaining one active group [group_start, group_end] at the tail of our output list merged:

    Case A: start <= group_end (overlap or shared endpoint)
      current_group:  group_start================group_end
      next (extends):                  start===========end   -> group_end becomes end
      next (nested):               start===end               -> group_end stays group_end!
    
    Case B: start > group_end (strict gap)
      current_group:  group_start======group_end
      next interval:                             start====end
      all later ones:                              start2=====...  (also >= start > group_end)
    

    Why is current_group permanently sealed in Case B? Because the list is sorted by start: every later interval starts at or after start, which already lies strictly right of group_end. Nothing later can reach back across that uncovered gap, so we close current_group and open [start, end] as the new active group.

    Two details prevent classic bugs: - Use <=, not <: When start == group_end, both closed intervals contain that boundary point (like 8 in [6, 8] and [8, 11]), so they must merge. - Only grow group_end, never shrink it: When [4, 6] follows [2, 8], end (6) is smaller than group_end (8), so we preserve max(group_end, end).

  4. Implement the sort-and-sweep pass

    Calling sorted(intervals) creates a new outer list in O(n log n) time without reordering the caller's input list. Likewise, whenever we open a group in merged, we allocate a fresh two-element list [start, end] rather than appending the caller's sublist reference—otherwise current_group[1] = end would mutate one of the caller's inner lists!

    def merge_intervals(intervals: list[list[int]]) -> list[list[int]]:
        if not intervals:
            return []
    
        # Phase 1: Sort intervals by [start, end] ascending; sorted() returns a new list
        # so the caller's outer list order is never mutated.
        ordered = sorted(intervals)
    
        # merged: list of disjoint [group_start, group_end] pairs ordered by group_start.
        # Copy the earliest interval into a fresh two-item list to avoid mutating input lists.
        first_start, first_end = ordered[0]
        merged: list[list[int]] = [[first_start, first_end]]
    
        # Phase 2: Sweep left to right, extending or sealing the active group at merged[-1].
        for start, end in ordered[1:]:
            current_group = merged[-1]
            group_end = current_group[1]
    
            # Closed intervals include both endpoints, so start == group_end shares that single
            # point and must merge (hence <= rather than <).
            if start <= group_end:
                # Take max(group_end, end) so a nested interval like [2, 3] inside [1, 10]
                # never shrinks the active group's right boundary.
                if end > group_end:
                    current_group[1] = end
            else:
                # Because ordered is sorted by start, every later interval also starts > group_end,
                # so current_group can never overlap anything else; start a new group.
                merged.append([start, end])
    
        return merged
    
  5. Trace Example 1 and Example 2 step by step

    Let's trace both examples to verify nested intervals, uncovered real gaps, and shared single-point boundaries:

    Example 1: intervals = [[10, 14], [2, 8], [4, 6], [12, 18]]
    Sorted:    ordered   = [[2, 8], [4, 6], [10, 14], [12, 18]]
    
      Seed with ordered[0]:   merged = [[2, 8]]
      Next [4, 6]:   start 4  <= group_end 8  -> nested (6 <= 8)    -> merged = [[2, 8]]
      Next [10, 14]: start 10 >  group_end 8  -> gap! New group     -> merged = [[2, 8], [10, 14]]
      Next [12, 18]: start 12 <= group_end 14 -> extend end to 18   -> merged = [[2, 8], [10, 18]]
      Return [[2, 8], [10, 18]]
    
    Example 2: intervals = [[6, 8], [0, 5], [8, 8], [8, 11]]
    Sorted:    ordered   = [[0, 5], [6, 8], [8, 8], [8, 11]]
    
      Seed with ordered[0]:   merged = [[0, 5]]
      Next [6, 8]:   start 6 >  group_end 5 -> gap (5.5 uncovered)  -> merged = [[0, 5], [6, 8]]
      Next [8, 8]:   start 8 <= group_end 8 -> shares point 8       -> merged = [[0, 5], [6, 8]]
      Next [8, 11]:  start 8 <= group_end 8 -> shares 8, end -> 11  -> merged = [[0, 5], [6, 11]]
      Return [[0, 5], [6, 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, end] ascending; sorted() returns a new list
        # so the caller's outer list order is never mutated.
        ordered = sorted(intervals)
    
        # merged: list of disjoint [group_start, group_end] pairs ordered by group_start.
        # Copy the earliest interval into a fresh two-item list to avoid mutating input lists.
        first_start, first_end = ordered[0]
        merged: list[list[int]] = [[first_start, first_end]]
    
        # Phase 2: Sweep left to right, extending or sealing the active group at merged[-1].
        for start, end in ordered[1:]:
            current_group = merged[-1]
            group_end = current_group[1]
    
            # Closed intervals include both endpoints, so start == group_end shares that single
            # point and must merge (hence <= rather than <).
            if start <= group_end:
                # Take max(group_end, end) so a nested interval like [2, 3] inside [1, 10]
                # never shrinks the active group's right boundary.
                if end > group_end:
                    current_group[1] = end
            else:
                # Because ordered is sorted by start, every later interval also starts > group_end,
                # so current_group can never overlap anything else; start a new group.
                merged.append([start, end])
    
        return merged
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine laying strips of masking tape along a wooden ruler to mark covered segments, where each strip [start, end] is a closed interval (a continuous range that includes both endpoint numbers and every real number between them). When the strips sit in a random pile, telling which ones link up into longer chains is awkward. If you first line up all the strips by their left edge from smallest to largest, the job becomes straightforward: pick up the leftmost strip as your active segment, and inspect each remaining strip in order. Whenever the next strip's left edge touches or lands inside your active segment (start <= group_end), glue them together and extend your right edge if the new strip reaches further right; whenever bare ruler separates them (start > group_end), no later strip can bridge back across that gap because every remaining strip starts even further to the right. Sorting geometric intervals by coordinate and scanning them in one pass is called a sweep-line algorithm.

Why does the naive approach fall short? Without sorting first, deciding which intervals belong together requires comparing every pair of intervals (or building a graph and finding connected components, meaning clusters of intervals linked directly or indirectly through chains of overlaps). With up to n = 100,000 intervals, testing all n * (n - 1) / 2 pairs takes roughly 5 billion checks (O(n^2) time), whereas sorting once brings every overlapping neighbor next to the active group in O(n log n) time.

Here is how the sweep works on Example 1 (intervals = [[10, 14], [2, 8], [4, 6], [12, 18]]):

Sorted by start: [[2, 8], [4, 6], [10, 14], [12, 18]]

1. Start with [2, 8]       -> merged = [[2, 8]]
2. Read [4, 6]:   4 <= 8   -> nested inside [2, 8], max(8, 6) stays 8 -> merged = [[2, 8]]
3. Read [10, 14]: 10 > 8   -> gap after 8, open new group [10, 14]    -> merged = [[2, 8], [10, 14]]
4. Read [12, 18]: 12 <= 14 -> overlaps [10, 14], extend end to 18     -> merged = [[2, 8], [10, 18]]

The returned ranges are disjoint (no two intervals share any point) and already ordered by start.

Complexity

  • Time: O(n log n), where n is len(intervals). Sorting the n two-element lists with Python's Timsort takes O(n log n) comparisons, and the single left-to-right sweep afterward inspects each interval once with O(1) constant-time comparisons and appends.
  • Space: O(n). sorted(intervals) allocates a list of n references so we do not reorder the caller's input, and merged holds up to n two-element lists when all intervals are disjoint.

Edge cases

  • Single interval ([[7, 7]]): Seeded into merged as a fresh copy and returned unchanged because ordered[1:] is empty.
  • Touching endpoints ([2, 6] and [6, 9], or [6, 8], [8, 8], and [8, 11]): Closed intervals include both endpoints, so sharing a single boundary point satisfies start <= group_end and merges them.
  • Consecutive integers ([0, 5] and [6, 8]): Because intervals cover continuous real points, 5.5 is uncovered; 6 > 5 keeps [0, 5] and [6, 8] separate.
  • Transitive overlap chains ([1, 4], [3, 7], [6, 10]): After sorting, [1, 4] and [3, 7] merge into [1, 7], whose updated group_end = 7 then absorbs [6, 10] into [1, 10].
  • Nested intervals ([4, 6] inside [2, 8]): Updating current_group[1] only when end > group_end prevents [4, 6] from shrinking [2, 8] down to [2, 6].
  • Duplicates and point intervals ([0, 0] repeated): Sorting places identical ranges side by side, and 0 <= 0 collapses all copies into one [0, 0].
  • Extreme negative and positive coordinates (-10^9 to 10^9): The sweep only compares endpoints without adding or multiplying them, avoiding integer overflow even in fixed-width 32-bit languages.

Common mistakes

  • Writing start < group_end instead of start <= group_end: Treats endpoints as open and wrongly leaves touching closed ranges like [6, 8] and [8, 11] unmerged.
  • Writing start <= group_end + 1: Coalesces consecutive integers like [0, 5] and [6, 8] into [0, 8], ignoring uncovered real numbers in (5, 6) and failing Example 2.
  • Unconditionally assigning current_group[1] = end: On [[2, 10], [3, 4], [6, 8]], overwriting 10 with 4 makes [6, 8] appear disconnected from [2, 10]. Always keep max(group_end, end).
  • Comparing against the previous input element ordered[i - 1] instead of merged[-1]: On [[2, 10], [3, 4], [6, 8]], [6, 8] does not intersect [3, 4], yet it still falls inside [2, 10].
  • Appending the original inner list ordered[0] directly into merged: Mutating merged[-1][1] = end would alter the caller's input sublist in place; copying [first_start, first_end] avoids side effects.

Alternative approaches

  • Endpoint event sweep: Convert each [start, end] into two events (start, OPEN) and (end, CLOSE), sort events by coordinate with OPEN ordered before CLOSE at ties (so touching endpoints stay active before closing), and maintain an active_count counter. A merged range opens when active_count rises from 0 to 1 and closes when it drops back to 0. This also runs in O(n log n) time and generalizes directly when computing peak overlap depth.
  • Graph connected components: Build an intersection graph over all interval pairs and traverse each component to compute [min_start, max_end]. Correct, but O(n^2) time and memory cannot handle n = 10^5.

Follow-up questions

  • How would you insert a single new interval into an already sorted, disjoint list? Because the existing list is already sorted and disjoint, you can skip sorting altogether and finish in O(n) time with one pass: copy all intervals with end < new_start, merge every interval satisfying start <= new_end into [min(start, new_start), max(end, new_end)], append that merged interval, and copy the remaining intervals. You can find the first and last overlapping indices in O(log n) using binary search, though building the updated Python list still takes O(n) time due to shifting elements.
  • What if intervals arrive in a live stream and you must query the merged list at any time? Store the disjoint intervals ordered by start inside a balanced binary search tree (a sorted tree structure that supports search, insertion, and deletion in O(log k) time for k stored intervals, such as std::map in C++ or SortedDict in Python). When [new_start, new_end] arrives, look up the predecessor and successor intervals that satisfy start <= new_end and end >= new_start, delete them from the tree, and insert their combined [min_start, max_end] interval; since every inserted interval can be deleted at most once, m stream arrivals take O(m log m) total time.
  • How do the rules change for half-open intervals [start, end)? A half-open interval [start, end) includes start and every real point strictly below end, excluding end itself, so [2, 6) and [6, 9) share zero points. However, in calendar and busy-time coalescing you usually still want back-to-back [2, 6) and [6, 9) merged into one continuous [2, 9) block (keeping start <= group_end), whereas if you only merge intervals that share positive overlap length you change the check to start < group_end—confirming which rule the caller wants is an essential clarifying question.

Follow-up questions

Similar questions

More Lime interview questions

All 1 Lime questions →