M30 · Greedy

Greedy Algorithms: Interval Scheduling and Merging Intervals

A greedy algorithm commits to the choice that looks best right now and never revisits it. For scheduling the most non-overlapping intervals, "earliest end first" is provably optimal; "shortest first" and "earliest start first" are not. This lesson traces both the selection and the merge sweep, proves the selection correct with an exchange argument, and shows with coin change and 0/1 knapsack where greedy breaks and dynamic programming takes over.

~40 minAdvancedC# · Python · Java · C++
Curriculum: M30 Greedy · 1 of 1 lessons available

You will be able to

  • Describe a greedy algorithm as a sequence of irrevocable choices, and name the two properties (greedy choice, optimal substructure) that make one correct.
  • Schedule a maximum set of non-overlapping intervals by sorting on end time, and handle half-open endpoints and ties deterministically.
  • Prove the earliest-end rule optimal with an exchange argument, and refute "shortest first" and "earliest start first" with small counterexamples.
  • Merge overlapping intervals into the disjoint blocks of their union, deciding explicitly whether touching intervals merge.
  • Recognise problems where greedy fails (non-canonical coin change, 0/1 knapsack, weighted intervals) and switch to dynamic programming.
  • Sort by several keys in C#, Python, Java and C++, knowing which library sorts are stable.

Helpful before this lesson

  • M13 Sorting — Stability, in-place sorting, the classic algorithms and what built-in sorts actually do.
  • M21 Heaps and Priority Queues — The array-backed heap, sift operations, O(n) heapify and heap sort.

Guidance only. Those modules are planned; the essentials are recapped here.

Visual walkthrough

The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

What makes an algorithm greedy

A greedy algorithm builds its answer one decision at a time. At each step it takes the option that looks best by some simple rule and never takes it back. There is no search over alternatives and no table of subproblems, which is why greedy algorithms are usually short and fast: often one sort and one linear scan.

The catch is that "looks best now" is not the same as "is best overall". A greedy algorithm is correct only when two things hold:

  • Greedy choice property. Some optimal solution contains the greedy first choice. Committing to it never rules out reaching an optimum.
  • Optimal substructure. After that choice, what is left is a smaller instance of the same problem, and an optimal answer to it combined with the choice is optimal for the whole.

Dynamic programming needs optimal substructure too. The difference is the first property: DP tries every choice and keeps the best, greedy trusts one. When the greedy choice property fails, the algorithm still runs and still returns something plausible. It is just wrong, so every greedy algorithm needs a proof or a counterexample, never a hunch.

You have already seen greedy algorithms: Dijkstra settles the closest unsettled node, and Kruskal's minimum spanning tree algorithm (built on union-find) adds the cheapest edge that does not close a cycle. Huffman coding, which merges the two least frequent symbols repeatedly, is another. Each comes with its own proof.

Interval scheduling

You have one room and a list of requested bookings, each with a start and an end time. Accept as many as possible so that no two accepted bookings overlap. This is interval scheduling, also called activity selection. Every booking is worth the same; only the count matters.

Endpoints: half-open intervals

Before any algorithm, decide what "overlap" means at the boundary. This lesson, the lab and all four implementations use half-open intervals [start, end): the interval contains start but not end. A booking [9, 10) ends exactly when [10, 11) begins, and the two do not conflict. Two half-open intervals a and b are compatible exactly when

a.end <= b.start  or  b.end <= a.start

Half-open intervals are the usual convention for time slots, array slices (a[lo:hi] in Python, [first, last) iterator ranges in C++) and calendar software, because adjacent ranges tile without gaps or double counting. If your data uses closed intervals [start, end], change >= to > in the check below; nothing else changes.

Three plausible rules

Which booking should the greedy algorithm accept first?

  1. The shortest one: it uses the least time.
  2. The one that starts first: it is the first to need a decision.
  3. The one that ends first: it frees the room soonest.

Only the third is always optimal. Small counterexamples sink the other two, and the lab has a preset for each:

  • Shortest first fails: [0, 6), [5, 8), [7, 13). The shortest, [5, 8), overlaps both others, so shortest-first accepts one booking. Earliest end accepts [0, 6) and [7, 13): two.
  • Earliest start fails: [0, 10), [1, 3), [4, 6), [7, 9). Earliest start takes [0, 10) and blocks everything else. Earliest end takes the three short bookings.

A rule that fails on four intervals fails on millions too; one counterexample is a complete refutation.

The algorithm

sort the intervals by end (ties: earlier start, then input order)
last_end = none
for each interval [s, e) in that order:
    if last_end is none or s >= last_end:
        take it
        last_end = e
    else:
        skip it        # overlaps the last interval taken

The tie-break does not change the number of intervals taken, but it does change which ones, and a fixed rule is what lets one fixture check the lab and all four languages. In the Ties and touching ends preset, three intervals end at 5; the one starting at 0 wins, and [5, 6) still fits afterwards because touching is allowed.

Notice that the scan compares each interval only with last_end, not with every interval taken so far. That is enough: everything taken ends at or before last_end, and every interval still to come ends at or after it, so the last one taken is the only one that can conflict.

Why earliest end first is optimal

Claim. Let g₁, g₂, …, gₖ be the intervals the greedy algorithm takes, in order, and let o₁, o₂, …, oₘ be any compatible set, sorted by end time. Then k ≥ m.

Greedy stays ahead. First show by induction that end(gᵢ) ≤ end(oᵢ) for every i ≤ k.

  • For i = 1: g₁ has the smallest end time of all intervals, so end(g₁) ≤ end(o₁).
  • For i > 1: oᵢ starts at or after end(oᵢ₋₁) (the o's are compatible and sorted), and by induction end(oᵢ₋₁) ≥ end(gᵢ₋₁). So oᵢ was still available when greedy picked gᵢ, and greedy picked the available interval with the smallest end: end(gᵢ) ≤ end(oᵢ).

Now suppose m > k. Then oₖ₊₁ exists and starts at or after end(oₖ) ≥ end(gₖ), so it was still compatible after greedy's last pick, and greedy would have taken it. Contradiction; so k ≥ m.

The exchange view says the same thing differently: take any optimal schedule and replace its first interval by g₁. Since g₁ ends no later, it conflicts with nothing the old first interval did not, so the schedule stays valid and the same size. Repeat on the rest. Step by step, any optimum turns into the greedy schedule without getting smaller. Exchange arguments are the standard way to prove a greedy choice: show that swapping the greedy choice into an optimal solution never makes it worse.

Merging intervals

A related sweep answers a different question: given intervals, what does their union look like? For example, which hours of the day is the room booked at all? The answer is a list of disjoint blocks.

sort the intervals by start (ties: earlier end, then input order)
current = first interval
for each next interval [s, e):
    if s <= current.end:              # overlaps or touches
        current.end = max(current.end, e)
    else:                             # a gap: current is finished
        emit current
        current = [s, e)
emit current

With half-open intervals, [1, 3) and [3, 5) share no point, but their union [1, 5) has no gap, so the merge joins them (s <= current.end, not <). If you need to keep touching intervals separate (say, distinct meetings that happen to be back to back), use < instead. The lab and the implementations merge touching intervals, and the tests compare them with a brute-force reference that marks every covered time unit and reads off the runs.

Sorting by start is what makes one pass enough: once an interval starts after the current block's end, every later interval starts even later, so nothing can reach back into the finished block. Note the max: an interval nested inside the block ([2, 3) inside [1, 10)) must not shrink it.

Complexity

Step Time Extra space
Sort O(n log n) O(n) for the index array or copy (the sort itself may add O(log n) to O(n))
Selection scan O(n): one comparison per interval O(k) for the result
Merge scan O(n): one comparison per interval after the first O(number of blocks)

The sort dominates: O(n log n) for both problems. If the intervals arrive already sorted, the scan alone is O(n). The Checks metric in the lab counts the scan comparisons only; the sort is shown as one step.

When greedy fails

Coin change with non-canonical coins

Make change for an amount using the fewest coins. Greedy says: always take the largest coin that fits. With coins {1, 5, 10, 25} that is optimal. With coins {1, 3, 4} and amount 6, greedy takes 4 + 1 + 1 (three coins), but 3 + 3 uses two. Taking the 4 felt best and was wrong, and greedy never reconsiders.

Coin systems where greedy is always optimal are called canonical; many real currencies are, but that is a property to check, not to assume. The general problem is solved by dynamic programming: best[a] = 1 + min(best[a − c]) over coins c ≤ a. See From recursion to dynamic programming for how such tables are built.

Knapsack: fractional yes, 0/1 no

With a capacity and items that have weights and values, the fractional knapsack (you may take part of an item) is solved greedily: sort by value per unit of weight and fill in that order, splitting the last item. An exchange argument proves it. In the 0/1 knapsack (all or nothing) the same rule fails: capacity 10, items (weight 6, value 30), (5, 20), (5, 20). The best ratio is the first item (5 per unit), which leaves room for nothing else: 30. The two others give 40. That problem needs the table in 0/1 knapsack.

Weighted intervals

Give each booking a value and maximise the total value instead of the count, and earliest end first breaks: [0, 10) worth 100 beats [0, 2) and [3, 5) worth 1 each. Weighted interval scheduling is a DP: sort by end, and for each interval choose the better of skipping it or taking it plus the best answer among intervals that end by its start (found with binary search). Still O(n log n), but it is no longer greedy.

The pattern: greedy works when one local quantity (end time, value density, edge weight) settles the decision for good. When the right choice depends on what comes later, you need to keep options open, and that is dynamic programming's job.

The teaching implementation

IntervalScheduling.Select / select sorts the indices by (end, start, index) and scans; Merge / merge sorts by (start, end) and sweeps. The listings are the exact files the tests run. Each language reads one shared fixture (the classic eleven-activity example, both failing rules, ties on end time, touching and duplicate intervals, nested intervals and empty input), then checks 500 random instances: the selection must be pairwise compatible and as large as a brute force over all subsets finds, and the merge must equal the runs of a covered-unit array.

Language notes

Language Sorting by several keys Stability
C# Array.Sort / List<T>.Sort with a comparison; value tuples compare element by element, so (a.End, a.Start, i).CompareTo(...) is a one-line multi-key comparison. Array.Sort and List<T>.Sort are unstable (introsort). LINQ OrderBy(...).ThenBy(...) is stable but allocates a new sequence.
Python sorted(items, key=lambda i: (end, start, i)); tuples compare lexicographically. sorted and list.sort are stable (Timsort), so sorting by one key keeps earlier order on ties.
Java Comparator.comparingInt(...).thenComparingInt(...). With boxed indices, write Comparator.<Integer>comparingInt(...) so the lambda types infer. A record gives a tidy interval type with equals for free. List.sort and Collections.sort on objects are stable; Arrays.sort on primitive arrays is not (it does not matter for primitives).
C++ A lambda comparing std::tuple(...) or std::tie(...); with C++20 ranges, std::ranges::sort(v, {}, &Interval::end) sorts by one projected key. std::sort is not stable; std::stable_sort is. Comparators must be a strict weak ordering (<, never <=).

Adding the input index as the last key makes every comparison total, so stability stops mattering: the order is fully determined in all four languages. Without it, two intervals with the same start and end could come out in either order from an unstable sort; for merging that is harmless (they are indistinguishable), for selection it changes which index is reported.

Common mistakes

  • Sorting by start for selection. That is the earliest-start rule, which fails.
  • Using > instead of >= with half-open intervals (or the reverse with closed ones): back-to-back bookings are wrongly rejected or wrongly accepted.
  • Comparing with every taken interval instead of just the last end. Correct, but O(n·k).
  • Forgetting max in the merge, so a nested interval shrinks the block.
  • Trusting a greedy rule because it worked on the examples. Try to break it with three or four intervals first; if you cannot, prove it.

Edge cases

  • No intervals: the schedule and the union are empty.
  • One interval: it is taken, and it is the only block.
  • Identical intervals: selection takes one (the smallest index); merge emits it once.
  • All intervals overlap one point: selection takes exactly one.
  • Intervals that only touch: all are taken, and they merge into one block.

Worked practice

1. Run earliest end first on [1, 4), [3, 5), [0, 6), [5, 7), [3, 9), [5, 9), [6, 10), [8, 11), [8, 12), [2, 14), [12, 16). Which intervals are taken?

Answer

[1, 4), [5, 7), [8, 11), [12, 16): four. After [1, 4) the last end is 4, so [3, 5) and [0, 6) are skipped; [5, 7) fits; [3, 9), [5, 9) and [6, 10) start before 7; [8, 11) fits; [8, 12) and [2, 14) start before 11; [12, 16) fits. This is the Eleven activities preset.

2. Does "fewest conflicts first" (take the interval that overlaps the fewest others) always work?

Answer

No. It survives the small cases above, but larger counterexamples exist: Kleinberg and Tardos (Algorithm Design, chapter 4) give one with eleven intervals, where the interval with the fewest conflicts blocks two intervals that every optimal schedule needs. A rule being "smart" is not a proof. Earliest end first has a proof.

3. Merge [8, 10), [1, 3), [2, 6), [15, 18), [3, 5), [16, 17).

Answer

Sorted by start: [1, 3), [2, 6), [3, 5), [8, 10), [15, 18), [16, 17). Blocks: [1, 6) ([3, 5) is inside it), [8, 10), [15, 18) ([16, 17) is nested).

4. Coins {1, 6, 10}, amount 12. What does greedy return, and what is optimal?

Answer

Greedy takes 10, then 1 and 1: three coins. Two 6s make two coins. {1, 6, 10} is not a canonical system; use the DP.

5. How many rooms are needed so that every booking can be accepted?

Answer

The maximum number of intervals that overlap at one moment. Sort all endpoints (with an end at time t before a start at time t, because the intervals are half-open), sweep while counting +1 at each start and −1 at each end, and take the maximum. O(n log n). Assigning bookings to rooms greedily, each to any room that is free, uses exactly that many.

Summary

  • A greedy algorithm makes one irrevocable choice per step; it is correct only with a proof (greedy choice + optimal substructure), and wrong rules are refuted by a single counterexample.
  • Interval scheduling: sort by end time and take every interval that starts at or after the last end. Optimal by "greedy stays ahead" or an exchange argument. O(n log n).
  • Merging: sort by start and extend the current block while the next start is at most its end. Decide explicitly whether touching intervals merge. O(n log n).
  • Shortest first and earliest start first fail; so does greedy coin change with non-canonical coins, 0/1 knapsack by value density and weighted interval scheduling: those need DP.

Full implementation

Interval selection and merging in four languages, each checked against one shared fixture (ties on end time, touching half-open intervals, duplicates, nested intervals, empty input) and 500 random instances: the selection is compared with a brute-force maximum over all subsets, the merge with the runs of a covered-unit array.

namespace Bekadan.Dsa.Examples.Greedy;
 
/// <summary>
/// Greedy sweeps over half-open intervals [Start, End): [1, 3) and [3, 5) do not overlap.
/// <see cref="Select"/> returns a maximum set of pairwise non-overlapping intervals
/// (earliest end first); <see cref="Merge"/> returns the disjoint blocks of their union
/// (touching intervals merge). Both sort once: O(n log n) time, O(n) extra space.
/// </summary>
public static class IntervalScheduling
{
    /// <summary>Input indices of the intervals taken, in the order taken.</summary>
    public static List<int> Select(IReadOnlyList<(int Start, int End)> intervals)
    {
        // Sort indices by (end, start, index); the index makes every tie deterministic.
        var order = Enumerable.Range(0, intervals.Count).ToArray();
        Array.Sort(order, (a, b) =>
            (intervals[a].End, intervals[a].Start, a).CompareTo((intervals[b].End, intervals[b].Start, b)));
        var taken = new List<int>();
        int? lastEnd = null;
        foreach (int i in order)
        {
            if (lastEnd is null || intervals[i].Start >= lastEnd)
            {
                taken.Add(i);
                lastEnd = intervals[i].End;
            }
            else
            {
                continue; // overlaps the last interval taken
            }
        }
        return taken;
    }
 
    /// <summary>The disjoint blocks of the union, left to right.</summary>
    public static List<(int Start, int End)> Merge(IReadOnlyList<(int Start, int End)> intervals)
    {
        var sorted = intervals.Select((iv, i) => (iv.Start, iv.End, Index: i)).ToList();
        sorted.Sort();  // tuples compare by start, then end, then index
        var blocks = new List<(int Start, int End)>();
        if (sorted.Count == 0)
            return blocks;
        var (start, end, _) = sorted[0];
        for (int k = 1; k < sorted.Count; k++)
        {
            var next = sorted[k];
            if (next.Start <= end)
            {
                end = Math.Max(end, next.End);
            }
            else
            {
                blocks.Add((start, end));
                (start, end) = (next.Start, next.End);
            }
        }
        blocks.Add((start, end));
        return blocks;
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Greedy/IntervalScheduling.cs

"""Greedy sweeps over half-open intervals [start, end): [1, 3) and [3, 5) do not overlap.
 
select() returns a maximum set of pairwise non-overlapping intervals (earliest end
first); merge() returns the disjoint blocks of their union (touching intervals merge).
Both sort once: O(n log n) time, O(n) extra space.
"""
 
Interval = tuple[int, int]
 
 
def select(intervals: list[Interval]) -> list[int]:
    """Input indices of the intervals taken, in the order taken."""
    # Sort indices by (end, start, index); the index makes every tie deterministic.
    order = sorted(range(len(intervals)), key=lambda i: (intervals[i][1], intervals[i][0], i))
    taken: list[int] = []
    last_end: int | None = None
    for i in order:
        start, end = intervals[i]
        if last_end is None or start >= last_end:
            taken.append(i)
            last_end = end
        else:
            continue  # overlaps the last interval taken
    return taken
 
 
def merge(intervals: list[Interval]) -> list[Interval]:
    """The disjoint blocks of the union, left to right."""
    ordered = sorted((s, e, i) for i, (s, e) in enumerate(intervals))  # by start, end, index
    blocks: list[Interval] = []
    if not ordered:
        return blocks
    start, end, _ = ordered[0]
    for next_start, next_end, _ in ordered[1:]:
        if next_start <= end:
            end = max(end, next_end)
        else:
            blocks.append((start, end))
            start, end = next_start, next_end
    blocks.append((start, end))
    return blocks

Tested on CPython 3.14.0 · examples/python/dsa_examples/interval_scheduling.py

package dev.bekadan.dsa.greedy;
 
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.IntStream;
 
/**
 * Greedy sweeps over half-open intervals [start, end): [1, 3) and [3, 5) do not overlap.
 * {@link #select} returns a maximum set of pairwise non-overlapping intervals (earliest end
 * first); {@link #merge} returns the disjoint blocks of their union (touching intervals
 * merge). Both sort once: O(n log n) time, O(n) extra space.
 */
public final class IntervalScheduling {
    private IntervalScheduling() {
    }
 
    /** A half-open interval [start, end). */
    public record Interval(int start, int end) {
    }
 
    /** Input indices of the intervals taken, in the order taken. */
    public static List<Integer> select(List<Interval> intervals) {
        // Sort indices by (end, start, index); the index makes every tie deterministic.
        List<Integer> order = IntStream.range(0, intervals.size()).boxed()
                .sorted(Comparator.<Integer>comparingInt(i -> intervals.get(i).end())
                        .thenComparingInt(i -> intervals.get(i).start())
                        .thenComparingInt(i -> i))
                .toList();
        List<Integer> taken = new ArrayList<>();
        Integer lastEnd = null;
        for (int i : order) {
            Interval iv = intervals.get(i);
            if (lastEnd == null || iv.start() >= lastEnd) {
                taken.add(i);
                lastEnd = iv.end();
            } else {
                continue; // overlaps the last interval taken
            }
        }
        return taken;
    }
 
    /** The disjoint blocks of the union, left to right. */
    public static List<Interval> merge(List<Interval> intervals) {
        // List.sort is stable, so equal (start, end) pairs keep their input order.
        List<Interval> sorted = new ArrayList<>(intervals);
        sorted.sort(Comparator.comparingInt(Interval::start).thenComparingInt(Interval::end));
        List<Interval> blocks = new ArrayList<>();
        if (sorted.isEmpty()) {
            return blocks;
        }
        int start = sorted.get(0).start();
        int end = sorted.get(0).end();
        for (Interval next : sorted.subList(1, sorted.size())) {
            if (next.start() <= end) {
                end = Math.max(end, next.end());
            } else {
                blocks.add(new Interval(start, end));
                start = next.start();
                end = next.end();
            }
        }
        blocks.add(new Interval(start, end));
        return blocks;
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/greedy/IntervalScheduling.java

#pragma once
 
#include <algorithm>
#include <cstddef>
#include <numeric>
#include <optional>
#include <tuple>
#include <vector>
 
namespace bekadan::dsa {
 
// A half-open interval [start, end): [1, 3) and [3, 5) do not overlap.
struct Interval {
    int start;
    int end;
    friend bool operator==(const Interval&, const Interval&) = default;
};
 
// Input indices of a maximum set of pairwise non-overlapping intervals (earliest end
// first), in the order taken. O(n log n) time, O(n) extra space.
inline std::vector<std::size_t> select_intervals(const std::vector<Interval>& intervals) {
    // Sort indices by (end, start, index); the index makes every tie deterministic.
    std::vector<std::size_t> order(intervals.size());
    std::iota(order.begin(), order.end(), std::size_t{0});
    std::sort(order.begin(), order.end(), [&](std::size_t a, std::size_t b) {
        return std::tuple(intervals[a].end, intervals[a].start, a) < std::tuple(intervals[b].end, intervals[b].start, b);
    });
    std::vector<std::size_t> taken;
    std::optional<int> last_end;
    for (const std::size_t i : order) {
        if (!last_end || intervals[i].start >= *last_end) {
            taken.push_back(i);
            last_end = intervals[i].end;
        } else {
            continue;  // overlaps the last interval taken
        }
    }
    return taken;
}
 
// The disjoint blocks of the union, left to right (touching intervals merge).
// O(n log n) time, O(n) extra space.
inline std::vector<Interval> merge_intervals(std::vector<Interval> intervals) {
    // std::sort is not stable, but equal (start, end) pairs are indistinguishable here.
    std::sort(intervals.begin(), intervals.end(), [](const Interval& a, const Interval& b) {
        return std::tie(a.start, a.end) < std::tie(b.start, b.end);
    });
    std::vector<Interval> blocks;
    if (intervals.empty()) return blocks;
    Interval current = intervals.front();
    for (std::size_t k = 1; k < intervals.size(); ++k) {
        const Interval& next = intervals[k];
        if (next.start <= current.end) {
            current.end = std::max(current.end, next.end);
        } else {
            blocks.push_back(current);
            current = next;
        }
    }
    blocks.push_back(current);
    return blocks;
}
 
}  // namespace bekadan::dsa

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/interval_scheduling.hpp

References