← Back to Algorithms, page 5

algorithms-0090 · Medium fresher

Interval scheduling: select the largest number of non-overlapping intervals, and from that compute the fewest intervals to remove so the rest do not overlap.

Sort intervals by end time and take each interval whose start is at or after the end of the last one taken. Finishing earliest leaves the most room for the rest, which an exchange argument proves. That is O(n log n) for the sort and O(1) extra space. The minimum removals is n minus the number kept.

Full answer

Problem

Given intervals [start, end), return the maximum number that can be chosen with no two overlapping (touching at an endpoint is allowed). Then return the minimum number of intervals to remove so that the remaining ones do not overlap.

Example: [[1, 3], [2, 4], [3, 5], [6, 7]] allows 3 ([1,3], [3,5], [6,7]). [[1, 2], [2, 3], [3, 4], [1, 3]] needs 1 removal. Three copies of [1, 2] need 2 removals.

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

Brute force

Try subsets from largest to smallest and check pairwise overlaps: O(2^n * n).

Optimal approach

  1. Sort by end time.
  2. last_end = -infinity, count = 0.
  3. For each (s, e): if s >= last_end, take it: count += 1, last_end = e.
  4. Removals = n - count.

Why it works

Let g be the interval with the earliest end. Take any optimal selection and replace its first interval with g: g ends no later, so it cannot overlap the second chosen interval, and the selection stays valid with the same size. So some optimal answer starts with g. Removing g and everything overlapping it leaves the same problem on the rest, and induction finishes the argument. Sorting by start time fails: one long early interval like [0, 10] can block three short ones, as the test shows.

Complexity

O(n log n) time for sorting, O(1) extra space beyond the sort.

Code

python
import random
from itertools import combinations


def max_non_overlapping(intervals):
    """Maximum number of pairwise non-overlapping [start, end) intervals.
    Greedy: sort by end, take every interval that starts at or after the last chosen end. O(n log n)."""
    count, last_end = 0, float("-inf")
    for s, e in sorted(intervals, key=lambda x: x[1]):
        if s >= last_end:
            count += 1
            last_end = e
    return count


def min_removals(intervals):
    """Fewest intervals to delete so the rest do not overlap."""
    return len(intervals) - max_non_overlapping(intervals)


def brute(intervals):
    for k in range(len(intervals), 0, -1):
        for combo in combinations(sorted(intervals), k):
            if all(combo[i][1] <= combo[i + 1][0] for i in range(k - 1)):
                return k
    return 0


if __name__ == "__main__":
    assert max_non_overlapping([[1, 3], [2, 4], [3, 5], [6, 7]]) == 3
    assert min_removals([[1, 2], [2, 3], [3, 4], [1, 3]]) == 1
    assert min_removals([[1, 2], [1, 2], [1, 2]]) == 2
    assert max_non_overlapping([]) == 0
    # sorting by start is wrong: one long early interval blocks three short ones
    assert max_non_overlapping([[0, 10], [1, 2], [3, 4], [5, 6]]) == 3
    rng = random.Random(90)
    for _ in range(800):
        iv = []
        for _ in range(rng.randint(0, 8)):
            s = rng.randint(0, 15)
            iv.append([s, s + rng.randint(1, 6)])
        assert max_non_overlapping(iv) == brute(iv)
    print("all tests passed")

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

Edge cases

Empty input (0). Identical intervals (keep one). Touching intervals [1,2] and [2,3] (compatible here; if the problem uses closed intervals, change >= to >). Negative coordinates.

Pattern

Earliest-finish-first greedy with an exchange argument. Related: minimum arrows to burst balloons (same sort, count groups), meeting rooms (can one person attend all), and weighted interval scheduling, where greedy fails and DP with binary search is needed.

python
import random
from itertools import combinations


def max_non_overlapping(intervals):
    """Maximum number of pairwise non-overlapping [start, end) intervals.
    Greedy: sort by end, take every interval that starts at or after the last chosen end. O(n log n)."""
    count, last_end = 0, float("-inf")
    for s, e in sorted(intervals, key=lambda x: x[1]):
        if s >= last_end:
            count += 1
            last_end = e
    return count


def min_removals(intervals):
    """Fewest intervals to delete so the rest do not overlap."""
    return len(intervals) - max_non_overlapping(intervals)


def brute(intervals):
    for k in range(len(intervals), 0, -1):
        for combo in combinations(sorted(intervals), k):
            if all(combo[i][1] <= combo[i + 1][0] for i in range(k - 1)):
                return k
    return 0


if __name__ == "__main__":
    assert max_non_overlapping([[1, 3], [2, 4], [3, 5], [6, 7]]) == 3
    assert min_removals([[1, 2], [2, 3], [3, 4], [1, 3]]) == 1
    assert min_removals([[1, 2], [1, 2], [1, 2]]) == 2
    assert max_non_overlapping([]) == 0
    # sorting by start is wrong: one long early interval blocks three short ones
    assert max_non_overlapping([[0, 10], [1, 2], [3, 4], [5, 6]]) == 3
    rng = random.Random(90)
    for _ in range(800):
        iv = []
        for _ in range(rng.randint(0, 8)):
            s = rng.randint(0, 15)
            iv.append([s, s + rng.randint(1, 6)])
        assert max_non_overlapping(iv) == brute(iv)
    print("all tests passed")

Sort by end and take compatible intervals; random sets are checked against exhaustive subset search, and a sort-by-start counterexample is included.

Complexity

Time: O(n log n). Space: O(1) extra besides sorting. Weighted versions need DP plus binary search, also O(n log n).

By level

Fresher: Sorts by end time and selects compatible intervals, tracing a small example. Shows why sorting by start can fail.

Mid: Gives the exchange argument and handles endpoint conventions. Connects the problem to minimum arrows and meeting room checks.

Senior: Contrasts with weighted interval scheduling and explains why greedy breaks there. Applies the idea to resource booking systems and explains how sorting dominates the cost at scale.

Key points

  • Sort by end time
  • Take an interval when it starts after the last chosen end
  • Exchange argument proves optimality
  • Removals = n - kept
  • Clarify open versus closed endpoints

Common mistakes

  • Sorting by start time
  • Sorting by length
  • Using > when touching intervals are allowed, or >= when they are not
  • Applying the greedy to weighted intervals

Follow-ups

  • How do you solve the weighted version?
  • What is the minimum number of points that hit every interval?
  • How many rooms are needed to hold all intervals?

Tips

  • State the exchange argument briefly
  • Show the sort-by-start counterexample
  • Ask about endpoint semantics

Evaluation rubric

  • Correct greedy
  • Proof or argument
  • Correct removal count
  • Correct complexity