← Back to Algorithms, page 5

algorithms-0091 · Medium mid

Merge overlapping intervals into a sorted list of disjoint intervals, and insert a new interval into an already merged list without sorting again.

Sort by start time, then walk the list: if the next interval starts at or before the end of the last merged block, extend that block's end to the larger end; otherwise start a new block. Sorting dominates at O(n log n). For inserting into an already sorted, disjoint list, copy the intervals that end before the new one, absorb those that overlap it, then copy the rest, all in O(n).

Full answer

Problem

Given closed intervals [start, end], merge all overlapping ones and return the result sorted by start. Follow-up: given a sorted list of disjoint intervals and a new interval, insert it and merge where needed.

Example: [[1,3], [2,6], [8,10], [15,18]] becomes [[1,6], [8,10], [15,18]]. [[1,4], [4,5]] becomes [[1,5]] because the endpoints touch. Inserting [4, 8] into [[1,2], [3,5], [6,7], [8,10]] gives [[1,2], [3,10]].

Constraints: up to 10^4 intervals; start <= end.

Brute force

Repeatedly scan all pairs and merge any two that overlap until nothing changes: O(n^2) per pass and up to n passes, O(n^3) worst case.

Optimal approach

Merge:

  1. Sort by start.
  2. For each [s, e]: if the output is non-empty and s <= out[-1][1], set out[-1][1] = max(out[-1][1], e); otherwise append [s, e].

Insert:

  1. Copy intervals with end < new_start.
  2. While intervals start at or before new_end, merge them into the new interval.
  3. Append the merged interval and then the remaining ones.

Why it works

After sorting by start, every interval that could overlap the current block must come right after it: an interval starting after the block's end, and everything after that, starts even later, so the block is final once a gap appears. Taking the max of ends handles intervals fully contained in the block. In the insert version, the input is already sorted and disjoint, so the three phases cover all positions exactly once.

Complexity

Merge: O(n log n) time for sorting, O(n) for the output. Insert: O(n) time, O(n) output.

Code

python
import random


def merge(intervals):
    """Merge overlapping closed intervals. Sort by start, extend the last block while it overlaps.
    O(n log n) time, O(n) output."""
    out = []
    for s, e in sorted(intervals):
        if out and s <= out[-1][1]:      # touching [1,3] and [3,5] merge because ends are inclusive
            out[-1][1] = max(out[-1][1], e)
        else:
            out.append([s, e])
    return out


def insert(intervals, new):
    """Insert into an already sorted, non-overlapping list in O(n) without re-sorting."""
    out, i, n = [], 0, len(intervals)
    s, e = new
    while i < n and intervals[i][1] < s:
        out.append(list(intervals[i]))
        i += 1
    while i < n and intervals[i][0] <= e:
        s, e = min(s, intervals[i][0]), max(e, intervals[i][1])
        i += 1
    out.append([s, e])
    return out + [list(x) for x in intervals[i:]]


def brute(intervals):
    """Mark covered half-steps on a number line (values are small ints)."""
    covered = set()
    for s, e in intervals:
        covered.update(range(2 * s, 2 * e + 1))
    out = []
    for x in sorted(covered):
        if out and x == out[-1][1] + 1:
            out[-1][1] = x
        else:
            out.append([x, x])
    return [[a // 2, b // 2] for a, b in out]


if __name__ == "__main__":
    assert merge([[1, 3], [2, 6], [8, 10], [15, 18]]) == [[1, 6], [8, 10], [15, 18]]
    assert merge([[1, 4], [4, 5]]) == [[1, 5]]
    assert merge([[1, 4], [2, 3]]) == [[1, 4]]              # contained interval
    assert merge([]) == [] and merge([[5, 5]]) == [[5, 5]]
    assert insert([[1, 2], [3, 5], [6, 7], [8, 10]], [4, 8]) == [[1, 2], [3, 10]]
    rng = random.Random(91)
    for _ in range(1000):
        iv = []
        for _ in range(rng.randint(0, 8)):
            s = rng.randint(0, 20)
            iv.append([s, s + rng.randint(0, 5)])
        m = merge(iv)
        assert m == brute(iv)
        new = sorted([rng.randint(0, 25), rng.randint(0, 25)])
        assert insert(m, new) == merge(m + [new])
    print("all tests passed")

Save as b91_merge_intervals.py and run python3 b91_merge_intervals.py. It prints all tests passed (Python 3.13.5).

Edge cases

Empty input. Single interval. Contained intervals ([1,4] and [2,3]). Touching endpoints (merge for closed intervals; for half-open intervals use < instead of <=). Zero-length intervals like [5,5]. Do not modify the caller's lists when that matters (the code copies on insert).

Pattern

Sort then sweep, keeping one open block. Related: interval list intersections (two pointers), employee free time (merge then find gaps), calendar booking with a sorted structure, and summary ranges.

python
import random


def merge(intervals):
    """Merge overlapping closed intervals. Sort by start, extend the last block while it overlaps.
    O(n log n) time, O(n) output."""
    out = []
    for s, e in sorted(intervals):
        if out and s <= out[-1][1]:      # touching [1,3] and [3,5] merge because ends are inclusive
            out[-1][1] = max(out[-1][1], e)
        else:
            out.append([s, e])
    return out


def insert(intervals, new):
    """Insert into an already sorted, non-overlapping list in O(n) without re-sorting."""
    out, i, n = [], 0, len(intervals)
    s, e = new
    while i < n and intervals[i][1] < s:
        out.append(list(intervals[i]))
        i += 1
    while i < n and intervals[i][0] <= e:
        s, e = min(s, intervals[i][0]), max(e, intervals[i][1])
        i += 1
    out.append([s, e])
    return out + [list(x) for x in intervals[i:]]


def brute(intervals):
    """Mark covered half-steps on a number line (values are small ints)."""
    covered = set()
    for s, e in intervals:
        covered.update(range(2 * s, 2 * e + 1))
    out = []
    for x in sorted(covered):
        if out and x == out[-1][1] + 1:
            out[-1][1] = x
        else:
            out.append([x, x])
    return [[a // 2, b // 2] for a, b in out]


if __name__ == "__main__":
    assert merge([[1, 3], [2, 6], [8, 10], [15, 18]]) == [[1, 6], [8, 10], [15, 18]]
    assert merge([[1, 4], [4, 5]]) == [[1, 5]]
    assert merge([[1, 4], [2, 3]]) == [[1, 4]]              # contained interval
    assert merge([]) == [] and merge([[5, 5]]) == [[5, 5]]
    assert insert([[1, 2], [3, 5], [6, 7], [8, 10]], [4, 8]) == [[1, 2], [3, 10]]
    rng = random.Random(91)
    for _ in range(1000):
        iv = []
        for _ in range(rng.randint(0, 8)):
            s = rng.randint(0, 20)
            iv.append([s, s + rng.randint(0, 5)])
        m = merge(iv)
        assert m == brute(iv)
        new = sorted([rng.randint(0, 25), rng.randint(0, 25)])
        assert insert(m, new) == merge(m + [new])
    print("all tests passed")

Sort-and-sweep merge and a linear insert, cross-checked against a number-line coverage brute force and against merge-after-append.

Complexity

Time: O(n log n) merge, O(n) insert. Space: O(n) output. For a stream of insertions, a balanced tree or sorted container keyed by start gives O(log n) per insert plus merged neighbours.

By level

Fresher: Sorts by start, merges with the last block, and handles containment with max. Traces the standard example.

Mid: Implements the linear insert, handles endpoint conventions, and explains why sorted order makes the sweep correct. Applies the method to free-time and intersection problems.

Senior: Discusses online interval sets with balanced trees, calendar systems with many users, and interval trees for overlap queries. Considers time zones and inclusive or exclusive boundaries in real scheduling data.

Key points

  • Sort by start
  • Extend the last block while starts are within its end
  • Use max of ends for contained intervals
  • Insert into a sorted list in three phases
  • Decide whether touching intervals merge

Common mistakes

  • Sorting by end time
  • Setting the end to the new interval's end instead of the max
  • Using < when closed intervals should merge on touch
  • Re-sorting for every insert

Follow-ups

  • How would you support many inserts and queries online?
  • How do you intersect two sorted interval lists?
  • How do you find free time slots across several calendars?

Tips

  • Ask whether touching intervals merge
  • Show the contained-interval case
  • Mention the O(n) insert without sorting

Evaluation rubric

  • Correct merge
  • Handles containment and touching
  • Correct insert
  • Correct complexity