Merge Overlapping Intervals

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

You are given a list intervals where each element [start, end] represents a closed interval on the number line (start <= end). Implement:

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

Combine all intervals that overlap or touch into consolidated intervals, and return the resulting disjoint intervals ordered by ascending start coordinate.

Follow these rules:

  • Closed-interval overlap: Given two intervals [a, b] and [c, d] with a <= c, they overlap whenever c <= b. Sharing a single boundary point (c == b) counts as overlapping and merges into [a, max(b, d)].
  • Edge cases: Return [] if intervals is empty. Properly handle single-element inputs, duplicate intervals, zero-length point intervals ([x, x]), and narrower intervals nested completely inside wider ones.

Examples

Example 1

Input:  intervals = [[6, 9], [1, 4], [3, 5], [12, 15]]
Output: [[1, 5], [6, 9], [12, 15]]

After ordering by start ([1, 4], [3, 5], [6, 9], [12, 15]), [1, 4] and [3, 5] overlap over [3, 4] and combine into [1, 5]. Neither [6, 9] nor [12, 15] touches any neighbor, so both remain separate.

Example 2

Input:  intervals = [[2, 7], [7, 10], [3, 5]]
Output: [[2, 10]]

[3, 5] lies strictly inside [2, 7], and [7, 10] meets [2, 7] at boundary point 7, so all three collapse into [2, 10].

Constraints

  • 0 <= len(intervals) <= 10^4
  • 0 <= start_i <= end_i <= 10^4

Step-by-step walkthrough

  1. Restate the problem and overlap rule

    Given a list of closed intervals [start, end] (each interval includes both endpoints, with start <= end, given in any order), we want to merge every overlapping or touching group into a single interval and return the resulting non-overlapping intervals sorted by start:

    Overlapping:  [1, 4] and [3, 5]   ->  [1, 5]            (share [3, 4])
    Touching:     [2, 7] and [7, 10]  ->  [2, 10]           (share point 7)
    Separated:    [1, 5] and [6, 9]   ->  [1, 5], [6, 9]    (gap between 5 and 6)
    

    Whenever a <= c, two intervals [a, b] and [c, d] overlap if and only if c <= b. An empty input list [] has zero intervals to merge and returns [].

  2. Why pairwise merging without sorting is too slow

    A direct brute-force idea is to scan every pair of intervals (i, j), fuse the first overlapping pair [a, b] and [c, d] into [min(a, c), max(b, d)], and repeat from scratch until a full pass finds zero overlaps.

    Why does that time out? - Checking all pairs in a list of length n takes O(n^2) comparisons. - Up to n - 1 merges can happen one at a time, giving O(n^3) worst-case time — hundreds of billions of operations when n = 10,000.

    The wasted effort comes from comparing intervals far apart on the number line (like [1, 4] and [12, 15]) over and over.

  3. Key idea: sort by start time so overlaps sit side by side

    Once we sort all intervals by start in ascending order (comparing [start, end] pairs sorts by start first and breaks ties by end), any interval that overlaps our current merged block must appear immediately next in the sorted sequence. Look at the three things that can happen when we compare the next sorted interval [start, end] against our active merged block [last_start, last_end]:

    Number line:  0  1  2  3  4  5  6  7  8  9  10  11  12
    Active block:       |--------------|                    [2, 7]
    Case A (nested):       |-----|                          [3, 5]:  3 <= 7  -> end stays max(7, 5) = 7
    Case B (extends):                  |--------|           [7, 10]: 7 <= 7  -> end grows to max(7, 10) = 10
    Case C (gap):                                    |--|   [11, 12]: 11 > 10 -> close [2, 10], open [11, 12]
    

    Two rules govern the entire left-to-right sweep: 1. Overlap or touch (start <= last_end): Fuse them by setting last_end = max(last_end, end). Using <= catches touching endpoints ([2, 7] and [7, 10]), and max(...) prevents a nested interval like [3, 5] from shrinking [2, 7] down to [2, 5]. 2. Strict gap (start > last_end): Because the list is sorted by start time, every later interval has later_start >= start > last_end. None of them can ever reach back into [last_start, last_end], so [last_start, last_end] is permanently finished and [start, end] opens a new block.

  4. Write the linear sweep cleanly

    To keep the code bug-free and friendly to callers: - Guard if not intervals: return [] right up front so we can safely seed merged with a copy of the first sorted interval [[first_start, first_end]]. - Use sorted(intervals) and fresh [start, end] lists so updating last_merged[1] never mutates the caller's input list behind their back. - Unpack last_merged = merged[-1] and last_end = last_merged[1] instead of repeating merged[-1][1].

    from typing import List
    
    
    def merge_intervals(intervals: List[List[int]]) -> List[List[int]]:
        if not intervals:
            return []
    
        # Phase 1: Sort a copy by start ascending (ties broken by end ascending) without mutating `intervals`.
        sorted_intervals = sorted(intervals)
    
        # merged: list of non-overlapping [start, end] blocks built in ascending start order.
        first_start, first_end = sorted_intervals[0]
        merged: List[List[int]] = [[first_start, first_end]]
    
        # Phase 2: Sweep left to right, extending the active block or starting a new one.
        for start, end in sorted_intervals[1:]:
            last_merged = merged[-1]
            last_end = last_merged[1]
    
            # Closed intervals touch or overlap whenever start <= last_end (e.g., [2, 7] and [7, 10] share 7).
            if start <= last_end:
                # Keep max(last_end, end) so a nested interval like [3, 5] inside [2, 7] never shrinks the block.
                last_merged[1] = max(last_end, end)
            else:
                # Every remaining interval starts >= `start` > `last_end`, so `last_merged` is permanently finished.
                merged.append([start, end])
    
        return merged
    
  5. Walk through Example 1 and Example 2

    Let's trace Example 1 ([[6, 9], [1, 4], [3, 5], [12, 15]]), which sorts to [[1, 4], [3, 5], [6, 9], [12, 15]]:

    Step | Current interval | last_merged | Check (start <= last_end?) | merged after step
    -----+------------------+-------------+----------------------------+-------------------------------
    init | [1, 4]           | -           | seed first block           | [[1, 4]]
      1  | [3, 5]           | [1, 4]      | 3 <= 4  -> max(4, 5) = 5   | [[1, 5]]
      2  | [6, 9]           | [1, 5]      | 6 <= 5 is False -> append  | [[1, 5], [6, 9]]
      3  | [12, 15]         | [6, 9]      | 12 <= 9 is False -> append | [[1, 5], [6, 9], [12, 15]]
    

    In Example 2 ([[2, 7], [7, 10], [3, 5]]), sorting produces [[2, 7], [3, 5], [7, 10]] and merged starts as [[2, 7]]. First [3, 5] has 3 <= 7, keeping max(7, 5) = 7. Next [7, 10] has 7 <= 7, extending [2, 7] to [2, max(7, 10)] = [2, 10].

  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 a copy by start ascending (ties broken by end ascending) without mutating `intervals`.
        sorted_intervals = sorted(intervals)
    
        # merged: list of non-overlapping [start, end] blocks built in ascending start order.
        first_start, first_end = sorted_intervals[0]
        merged: List[List[int]] = [[first_start, first_end]]
    
        # Phase 2: Sweep left to right, extending the active block or starting a new one.
        for start, end in sorted_intervals[1:]:
            last_merged = merged[-1]
            last_end = last_merged[1]
    
            # Closed intervals touch or overlap whenever start <= last_end (e.g., [2, 7] and [7, 10] share 7).
            if start <= last_end:
                # Keep max(last_end, end) so a nested interval like [3, 5] inside [2, 7] never shrinks the block.
                last_merged[1] = max(last_end, end)
            else:
                # Every remaining interval starts >= `start` > `last_end`, so `last_merged` is permanently finished.
                merged.append([start, end])
    
        return merged
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine strips of masking tape tossed onto a ruler at random positions, where each strip represents a closed interval [start, end] (an interval that includes both endpoints, so [2, 7] and [7, 10] touch at 7 and form one continuous strip [2, 10]). Spotting which strips connect while they sit in random order is messy, so you first line all strips up by their left edge (start) from left to right. Once sorted, a single greedy sweep (one left-to-right pass that makes local decisions without ever backtracking) suffices: keep a finger on the right edge of your current merged strip, extend it whenever the next strip starts at or before your finger, and start a brand-new strip whenever a gap appears.

Why do obvious alternatives fail? Repeatedly scanning all pairs of intervals for overlaps without sorting first can take O(n^2) checks per merge and O(n^3) time overall, which times out on 10,000 intervals. Another common trap is sorting first but comparing interval i only against sorted_intervals[i - 1] instead of merged[-1]: on [[1, 12], [2, 4], [6, 8]], [6, 8] does not touch [2, 4], yet both sit completely inside [1, 12].

Let's trace intervals = [[6, 9], [1, 4], [3, 5]]: 1. Sort by start coordinate -> [[1, 4], [3, 5], [6, 9]], and start merged = [[1, 4]]. 2. Next is [3, 5]: 3 <= 4, so it overlaps [1, 4] and extends it to [1, max(4, 5)] = [1, 5]. 3. Next is [6, 9]: 6 > 5, so [1, 5] is finished and merged becomes [[1, 5], [6, 9]].

Complexity

Let n be len(intervals).

  • Time: O(n log n), because sorted(intervals) uses Timsort (Python's built-in hybrid merge-and-insertion sorting algorithm) to order the n two-element lists in O(n log n) comparisons, and the single sweep afterward visits each of the n intervals once with O(1) comparisons and list appends per step.
  • Space: O(n), because sorted(intervals) allocates a list of n references and merged holds up to n two-element lists when all input intervals are disjoint.

Edge cases

  • Empty list ([]): Caught immediately by if not intervals: return [].
  • Single interval ([[4, 7]]): Loop over sorted_intervals[1:] does zero iterations and returns a fresh copy [[4, 7]].
  • Touching endpoints ([[2, 7], [7, 10]]): 7 <= 7 evaluates to True, merging them into [[2, 10]].
  • Adjacent integers with a gap ([[1, 2], [3, 4]]): No real number belongs to both [1, 2] and [3, 4] (3 > 2), so they remain separate.
  • Nested intervals ([[2, 7], [3, 5]]): max(7, 5) preserves 7 instead of shrinking the right edge to 5.
  • Duplicate and zero-length point intervals ([[0, 0], [0, 0], [5, 5], [5, 9]]): Handled seamlessly by start <= last_end and max(...), producing [[0, 0], [5, 9]].

Common mistakes

  • Forgetting to sort intervals first: Only merges intervals that happen to sit next to each other in the raw input.
  • Writing start < last_end instead of start <= last_end: Leaves touching intervals like [2, 7] and [7, 10] unmerged and fails Example 2.
  • Writing last_merged[1] = end without max(last_end, end): Truncates [2, 7] to [2, 5] whenever a shorter nested interval [3, 5] follows it.
  • Comparing sorted_intervals[i] to sorted_intervals[i - 1] instead of merged[-1]: Misses overlaps whenever a short nested interval sits between a long outer interval and another inner interval.
  • Mutating the caller's inner [start, end] lists directly: Appending sorted_intervals[0] without copying [first_start, first_end] means last_merged[1] = ... silently modifies the caller's original list object.

Alternative approaches

  • Coordinate bucketing (O(n + M) using the bounded range 0 <= end <= 10^4): Create an array max_end_at_start of size M = 10,001 initialized to -1, record the largest end for each start in O(n), and sweep x from 0 to 10,000 extending or closing the active block. This avoids the O(n log n) comparison sort when coordinates are small non-negative integers, though it breaks or wastes memory if coordinates can be negative, floating-point, or large timestamps.

Follow-up questions

  • Can you analyze the runtime and memory cost, and reduce auxiliary memory if mutating the input list is allowed? Our solution runs in O(n log n) time and O(n) space. If the caller permits an in-place algorithm (an algorithm that overwrites the input list directly rather than allocating a separate output list), call intervals.sort() and maintain a write index at the front of intervals: extend intervals[write - 1][1] on overlap, or store [start, end] into intervals[write] and increment write, then slice away the tail with del intervals[write:]. Aside from the sorting routine's internal workspace (up to O(n) temporary pointers in Python's Timsort, or O(1) extra space with heapsort), our merge pass uses O(1) auxiliary variables.

python def merge_in_place(intervals): intervals.sort() write = 0 for start, end in intervals: if write > 0 and start <= intervals[write - 1][1]: intervals[write - 1][1] = max(intervals[write - 1][1], end) else: intervals[write] = [start, end] write += 1 del intervals[write:] return intervals

  • How would you adapt this algorithm for billions of timestamp ranges stored on disk that exceed available RAM? Switching from small integers to arbitrary timestamps leaves start <= last_end and max(last_end, end) unchanged (once endpoint inclusivity is agreed upon). Because the dataset exceeds RAM, replace in-memory sorted() with external merge sort (reading RAM-sized chunks from disk, sorting each chunk in memory, writing sorted run files back to disk, and streaming all runs together through a min-heap — a binary tree structure that pops the earliest-starting interval next). As the min-heap yields intervals in ascending start order, the merge step keeps just one active [cur_start, cur_end] pair in memory (O(1) RAM) and flushes each completed range to output storage whenever start > cur_end.
  • If the intervals arrive pre-sorted by start coordinate, how fast can you merge them? Skip sorted(intervals) altogether and run only Phase 2's single left-to-right pass, lowering total time from O(n log n) to O(n) with O(1) extra workspace beyond the output list. O(n) is optimal because every interval must be inspected at least once to verify whether it extends or separates from its predecessor.

Follow-up questions

Similar questions

More Atlassian interview questions

All 55 Atlassian questions →