Lesson 16 · Problem-solving methods

Interval Algorithms

An interval is a start and an end. Almost every question about a list of them is answered by one comparison, max of the starts against min of the ends, applied after sorting the list so that intervals which can touch end up next to each other.

Interval Algorithms concept diagramInterval X from 4 to 8 is compared with six intervals Y: 0 to 2 (before, no overlap), 1 to 4 (touching at 4, overlap only if end points count), 2 to 6 (overlap 4 to 6), 5 to 7 (inside, overlap 5 to 7), 3 to 10 (contains X, overlap 4 to 8) and 9 to 11 (after, no overlap). In every case the intervals overlap exactly when the latest start is at most the earliest end.Y relative to XX = [4, 8] (grey), Y (blue)max start ≤ min end ?beforeY = [0, 2]4 ≤ 2 ?no overlaptouchingY = [1, 4]4 ≤ 4 ?closed yes, half-open nooverlappingY = [2, 6]4 ≤ 6 ?yes, shared [4, 6]insideY = [5, 7]5 ≤ 7 ?yes, shared [5, 7]containingY = [3, 10]4 ≤ 8 ?yes, shared [4, 8]afterY = [9, 11]9 ≤ 8 ?no overlap024681012one test for all six: max(s₁, s₂) ≤ min(e₁, e₂) · shared part [max start, min end]
1

An Interval Is Just Two Numbers

An interval is a pair [start, end] with start ≤ end: a meeting from 9 to 11, a booking from day 3 to day 5, a range of addresses. Interval problems hand you a list of these and ask about overlap: merge the ones that touch, find where two lists agree, remove as few as possible so none clash.

Before writing any code, settle one question: does the interval include its end? A closed interval [4, 7] contains 4 and 7. A half-open interval [4, 7) contains 4 but stops just before 7. Meetings and time slots are usually half-open, so a meeting ending at 4 does not clash with one starting at 4. Many array problems use closed ranges, where those two would share the point 4.

  • Closed [s, e]: touching at a point counts as overlap
  • Half-open [s, e): touching does not count
  • Pick one and use the matching comparison, ≤ or <, everywhere
2

Check if Two Intervals Overlap

There are six ways two intervals can sit relative to each other, but one test covers all of them. The latest start is max(s₁, s₂) and the earliest end is min(e₁, e₂). The intervals share something exactly when the latest start comes no later than the earliest end: max(s₁, s₂) ≤ min(e₁, e₂) for closed intervals, with < for half-open ones.

The same two numbers give the intersection of two intervals: [max start, min end], which is empty when the test fails. For [1, 4] and [2, 6] that is [2, 4]. For [4, 7] and [8, 11] the latest start 8 is past the earliest end 7, so they do not overlap.

Writing the four separate cases (starts inside, ends inside, contains, is contained) is a common source of bugs, because it is easy to forget one. The single comparison has no cases to forget.

  • Overlap: max(s₁, s₂) ≤ min(e₁, e₂)
  • Intersection: [max(s₁, s₂), min(e₁, e₂)] when that is not empty
  • No overlap: one ends before the other starts, e₁ < s₂ or e₂ < s₁
3

Sort First, Then One Pass

Comparing every pair costs O(n²). Sorting fixes that. Once the list is sorted by start, any interval that can overlap the block you are building comes right after it, so a single scan sees every overlap. The sort is O(n log n) and the scan O(n).

The sort key depends on the question. Sort by start when you build something up from the left: merging, inserting, intersecting. Sort by end when you choose which intervals to keep: the interval that ends first leaves the most room for the rest, which is the activity selection argument.

  • Merge, insert, intersect: sort by start
  • Keep the most non-overlapping intervals, or remove the fewest: sort by end
  • Count how many overlap at once: split into start and end events (see below)
Key reference

Terms, operations, and practical uses

Key terms

  • Closed interval[s, e] includes both end points, so ranges that touch overlap.
  • Half-open interval[s, e) includes s but not e, so ranges that touch do not overlap.
  • Overlap testmax of the starts ≤ min of the ends.
  • Merged blockThe interval being grown during a merge; its end is the largest end seen so far.
Implementation

Code in Python, C++ and Java

def overlaps(a, b):
    return max(a[0], b[0]) <= min(a[1], b[1])


def merge(intervals):
    merged = []
    for start, end in sorted(intervals):
        if merged and start <= merged[-1][1]:
            merged[-1][1] = max(merged[-1][1], end)
        else:
            merged.append([start, end])
    return merged


def insert(merged, new):
    left = [iv for iv in merged if iv[1] < new[0]]
    right = [iv for iv in merged if iv[0] > new[1]]
    middle = [iv for iv in merged if not (iv[1] < new[0] or iv[0] > new[1])]
    start = min([new[0]] + [iv[0] for iv in middle])
    end = max([new[1]] + [iv[1] for iv in middle])
    return left + [[start, end]] + right


def intersect(xs, ys):
    i = j = 0
    out = []
    while i < len(xs) and j < len(ys):
        lo, hi = max(xs[i][0], ys[j][0]), min(xs[i][1], ys[j][1])
        if lo <= hi:
            out.append([lo, hi])
        if xs[i][1] < ys[j][1]:
            i += 1
        else:
            j += 1
    return out


meetings = [[8, 11], [1, 4], [11, 12], [4, 7], [9, 13], [2, 6]]
merged = merge(meetings)
print("overlap [1,4] [2,6]:", overlaps([1, 4], [2, 6]))
print("overlap [4,7] [8,11]:", overlaps([4, 7], [8, 11]))
print("merged:", merged)
print("covered length:", sum(e - s for s, e in merged))
print("insert [7,8]:", insert(merged, [7, 8]))
print("intersect with [[5,9],[12,15]]:", intersect(merged, [[5, 9], [12, 15]]))
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;

using Interval = vector<int>;

bool overlaps(const Interval& a, const Interval& b) {
    return max(a[0], b[0]) <= min(a[1], b[1]);
}

vector<Interval> mergeAll(vector<Interval> intervals) {
    sort(intervals.begin(), intervals.end());
    vector<Interval> merged;
    for (const Interval& iv : intervals) {
        if (!merged.empty() && iv[0] <= merged.back()[1])
            merged.back()[1] = max(merged.back()[1], iv[1]);
        else
            merged.push_back(iv);
    }
    return merged;
}

vector<Interval> insertOne(const vector<Interval>& merged, Interval add) {
    vector<Interval> out;
    size_t i = 0;
    while (i < merged.size() && merged[i][1] < add[0]) out.push_back(merged[i++]);
    while (i < merged.size() && merged[i][0] <= add[1]) {
        add[0] = min(add[0], merged[i][0]);
        add[1] = max(add[1], merged[i][1]);
        i++;
    }
    out.push_back(add);
    while (i < merged.size()) out.push_back(merged[i++]);
    return out;
}

vector<Interval> intersect(const vector<Interval>& xs, const vector<Interval>& ys) {
    vector<Interval> out;
    size_t i = 0, j = 0;
    while (i < xs.size() && j < ys.size()) {
        int lo = max(xs[i][0], ys[j][0]), hi = min(xs[i][1], ys[j][1]);
        if (lo <= hi) out.push_back({lo, hi});
        if (xs[i][1] < ys[j][1]) i++; else j++;
    }
    return out;
}

string show(const vector<Interval>& v) {
    string s = "[";
    for (size_t i = 0; i < v.size(); i++)
        s += (i ? ", [" : "[") + to_string(v[i][0]) + ", " + to_string(v[i][1]) + "]";
    return s + "]";
}

int main() {
    vector<Interval> meetings = {{8, 11}, {1, 4}, {11, 12}, {4, 7}, {9, 13}, {2, 6}};
    vector<Interval> merged = mergeAll(meetings);
    int covered = 0;
    for (const Interval& iv : merged) covered += iv[1] - iv[0];
    cout << "overlap [1,4] [2,6]: " << (overlaps({1, 4}, {2, 6}) ? "True" : "False") << "\n";
    cout << "overlap [4,7] [8,11]: " << (overlaps({4, 7}, {8, 11}) ? "True" : "False") << "\n";
    cout << "merged: " << show(merged) << "\n";
    cout << "covered length: " << covered << "\n";
    cout << "insert [7,8]: " << show(insertOne(merged, {7, 8})) << "\n";
    cout << "intersect with [[5,9],[12,15]]: " << show(intersect(merged, {{5, 9}, {12, 15}})) << "\n";
}
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {
    static boolean overlaps(int[] a, int[] b) {
        return Math.max(a[0], b[0]) <= Math.min(a[1], b[1]);
    }

    static List<int[]> merge(int[][] intervals) {
        int[][] sorted = intervals.clone();
        Arrays.sort(sorted, (x, y) -> x[0] != y[0] ? Integer.compare(x[0], y[0]) : Integer.compare(x[1], y[1]));
        List<int[]> merged = new ArrayList<>();
        for (int[] iv : sorted) {
            if (!merged.isEmpty() && iv[0] <= merged.get(merged.size() - 1)[1]) {
                int[] last = merged.get(merged.size() - 1);
                last[1] = Math.max(last[1], iv[1]);
            } else {
                merged.add(new int[] {iv[0], iv[1]});
            }
        }
        return merged;
    }

    static List<int[]> insert(List<int[]> merged, int[] add) {
        List<int[]> out = new ArrayList<>();
        int s = add[0], e = add[1], i = 0;
        while (i < merged.size() && merged.get(i)[1] < s) out.add(merged.get(i++));
        while (i < merged.size() && merged.get(i)[0] <= e) {
            s = Math.min(s, merged.get(i)[0]);
            e = Math.max(e, merged.get(i)[1]);
            i++;
        }
        out.add(new int[] {s, e});
        while (i < merged.size()) out.add(merged.get(i++));
        return out;
    }

    static List<int[]> intersect(List<int[]> xs, int[][] ys) {
        List<int[]> out = new ArrayList<>();
        int i = 0, j = 0;
        while (i < xs.size() && j < ys.length) {
            int lo = Math.max(xs.get(i)[0], ys[j][0]), hi = Math.min(xs.get(i)[1], ys[j][1]);
            if (lo <= hi) out.add(new int[] {lo, hi});
            if (xs.get(i)[1] < ys[j][1]) i++; else j++;
        }
        return out;
    }

    static String show(List<int[]> v) {
        StringBuilder sb = new StringBuilder("[");
        for (int i = 0; i < v.size(); i++)
            sb.append(i > 0 ? ", " : "").append("[").append(v.get(i)[0]).append(", ").append(v.get(i)[1]).append("]");
        return sb.append("]").toString();
    }

    public static void main(String[] args) {
        int[][] meetings = {{8, 11}, {1, 4}, {11, 12}, {4, 7}, {9, 13}, {2, 6}};
        List<int[]> merged = merge(meetings);
        int covered = 0;
        for (int[] iv : merged) covered += iv[1] - iv[0];
        System.out.println("overlap [1,4] [2,6]: " + (overlaps(new int[] {1, 4}, new int[] {2, 6}) ? "True" : "False"));
        System.out.println("overlap [4,7] [8,11]: " + (overlaps(new int[] {4, 7}, new int[] {8, 11}) ? "True" : "False"));
        System.out.println("merged: " + show(merged));
        System.out.println("covered length: " + covered);
        System.out.println("insert [7,8]: " + show(insert(merged, new int[] {7, 8})));
        System.out.println("intersect with [[5,9],[12,15]]: " + show(intersect(merged, new int[][] {{5, 9}, {12, 15}})));
    }
}
Watch it run

Step through it

Running on [8,11], [1,4], [11,12], [4,7], [9,13], [2,6]

closed intervals · overlap when start ≤ block end0246810121416D [8, 11]A [1, 4]F [11, 12]C [4, 7]E [9, 13]B [2, 6]ANSWER(empty)input order: D A F C E Bclosed: [1, 4] and [4, 7] share the point 4, so they overlap
Step 1

Six intervals, unsorted

Each bar is a closed interval, so it includes both end points. They arrive in no particular order. The goal is to merge every group that overlaps into one interval.

Output
1 / 13
4

Merging Overlapping Intervals

  1. Sort the intervals by start
  2. Open a block with the first interval
  3. For each next interval: if its start ≤ the block's end, it overlaps, so set the block's end to the larger of the two ends
  4. Otherwise close the block, add it to the answer, and open a new block with this interval
  5. Close the last block at the end

Take the six intervals [8, 11], [1, 4], [11, 12], [4, 7], [9, 13] and [2, 6], treated as closed. Sorted by start they read [1, 4], [2, 6], [4, 7], [8, 11], [9, 13], [11, 12], and merging gives [1, 7] and [8, 13].

  • A closed block never reopens: every later interval starts even further right
  • [11, 12] lies inside [8, 13]. Setting the end to the newest end would shrink the block to [8, 12]
  • Skipping the sort is the other classic bug: the tracer shows it losing [1, 7] entirely
5

Inserting and Intersecting

To insert one new interval into a list that is already merged and sorted, no new sort is needed. Copy every interval that ends before the new one starts, absorb every interval it overlaps by widening it, then copy the rest. Inserting [7, 8] into [1, 7], [8, 13] touches both, so the answer collapses to [1, 13]. That takes O(n).

To intersect two sorted, merged lists, walk them with two pointers. Compute the intersection of the two current intervals, keep it if it is not empty, then step past whichever interval ends first, since it cannot meet anything further on in the other list. [1, 7], [8, 13] against [5, 9], [12, 15] gives [5, 7], [8, 9] and [12, 13].

  • Insert: before, overlapping (widen), after; O(n) on a merged list
  • Intersect: two pointers, advance the one that ends first; O(n + m)
6

Why the End-Point Rule Changes Answers

Ask for the fewest intervals to remove so that none of the six overlap. Sort by end and keep each interval that starts after the last one kept. With half-open meetings, [1, 4), [4, 7), [8, 11) and [11, 12) can all stay, and only [2, 6) and [9, 13) go: 2 removals. Treat the same numbers as closed and [4, 7] now shares the point 4 with [1, 4], so only [1, 4] and [8, 11] survive: 4 removals.

Same algorithm, same numbers, a different answer, decided entirely by ≤ versus <. Read the problem statement for that rule before anything else.

  • Half-open: 2 removals; closed: 4 removals
  • The only change in code is one comparison
7

Cost and Edge Cases

Every technique here is O(n log n) for the sort plus O(n) for the pass, with O(n) space for the answer (or O(1) extra if you merge in place over the sorted array). If the input is already sorted, the sort drops out and the pass alone is linear.

  • Empty list: return an empty list; one interval: return it unchanged
  • Nested intervals: always take the larger end
  • Touching intervals: follow the closed or half-open rule
  • Equal starts: the sort order among them does not matter for merging
  • Unsorted input: sort first, or the scan misses overlaps
8

When Pairs Are Not Enough

Everything above compares an interval with its neighbour. Some questions ask about many intervals at once: how many meetings run at the busiest moment, or how much of the line is covered. Those are answered by turning each interval into a start event and an end event and scanning them in order, which is the sweep line algorithm. For a set that keeps changing while you query it, an interval tree finds every overlap with a new range in O(log n + k).

  • Neighbour comparisons: merge, insert, intersect, remove
  • Counting at a moment: sweep line
  • Queries on a changing set: interval tree
9

Related Problems

Each of these is one of the patterns above, usually the merge or the end-sorted keep.