Greedy algorithms

Build a solution by always taking the choice that looks best right now, never reconsidering: fast and simple, and optimal only for problems with the right structure.

Description

A greedy algorithm makes the locally best choice at each step and never goes back. Pick the meeting that ends earliest; add the cheapest edge that doesn't create a cycle; give the largest coin that fits. It's usually simple and fast, often O(n log n) because of a sort.

Greedy works when the problem has the greedy-choice property (a locally best choice is part of some globally best solution) and optimal substructure. Proving that is the real work, usually with an "exchange argument": any optimal solution can be changed to include the greedy choice without getting worse.

Famous greedy algorithms that are optimal: interval scheduling by earliest finish time, Kruskal's and Prim's minimum spanning trees, Dijkstra's shortest paths, and Huffman coding for compression.

Greedy can also be confidently wrong. Making change for 6 with coins of 1, 3 and 4, greedy takes 4 + 1 + 1 (three coins), while 3 + 3 uses two. When greedy isn't provably optimal, dynamic programming finds the true optimum, and greedy may still serve as a fast approximation.

How it works

meetingstartendkeptstandup910✓design912review1011✓lunch talk1113✓1:11213retro1314✓

Meeting requests sorted by end time. Greedy keeps each one that starts after the last kept one ends.

  1. row 0: standup, 9, 10, ✓
  2. row 1: design, 9, 12,
  3. row 2: review, 10, 11, ✓
  4. row 3: lunch talk, 11, 13, ✓
  5. row 4: 1:1, 12, 13,
  6. row 5: retro, 13, 14, ✓
Meeting requests sorted by end time. Greedy keeps each one that starts after the last kept one ends.

Complexity

OperationAverageWorst
Interval schedulingSorting by end time dominates.O(n log n)O(n log n)
Huffman codingO(n log n)O(n log n)
Kruskal's MSTO(E log E)O(E log E)

Space: Usually O(1) to O(n) beyond the input

TypeScript implementation

Interval scheduling (provably optimal), and greedy coin change compared with dynamic programming to show when greedy fails.

greedy-algorithms.ts
// Greedy interval scheduling (optimal), and greedy coin change (not always).

type Meeting = { name: string; start: number; end: number };

/** Most non-overlapping meetings: always keep the one that ends first. */
export function schedule(meetings: Meeting[]): Meeting[] {
  const kept: Meeting[] = [];
  let free = -Infinity;
  for (const m of [...meetings].sort((a, b) => a.end - b.end)) {
    if (m.start >= free) {
      kept.push(m);
      free = m.end;
    }
  }
  return kept;
}

export function greedyCoins(amount: number, coins: number[]): number[] {
  const out: number[] = [];
  for (const c of [...coins].sort((a, b) => b - a)) while (amount >= c) { out.push(c); amount -= c; }
  return out;
}

/** Fewest coins, by dynamic programming, for comparison. */
export function fewestCoins(amount: number, coins: number[]): number {
  const best = [0, ...new Array(amount).fill(Infinity)];
  for (let a = 1; a <= amount; a++) for (const c of coins) if (c <= a) best[a] = Math.min(best[a], best[a - c] + 1);
  return best[amount];
}

export function demo(): string[] {
  const day: Meeting[] = [
    { name: "standup", start: 9, end: 10 }, { name: "design", start: 9, end: 12 },
    { name: "review", start: 10, end: 11 }, { name: "lunch talk", start: 11, end: 13 },
    { name: "1:1", start: 12, end: 13 }, { name: "retro", start: 13, end: 14 },
  ];
  return [
    `meetings kept: ${schedule(day).map((m) => m.name).join(", ")}`,
    `coins for 30 with [25, 10, 5, 1]: greedy ${greedyCoins(30, [25, 10, 5, 1]).join("+")} (optimal: ${fewestCoins(30, [25, 10, 5, 1])} coins)`,
    `coins for 6 with [4, 3, 1]: greedy ${greedyCoins(6, [4, 3, 1]).join("+")}, but the optimum is ${fewestCoins(6, [4, 3, 1])} coins (3+3)`,
  ];
}

When to use it

Use it when

  • The problem is known to have the greedy-choice property: scheduling by end time, MSTs, Huffman coding.
  • You need a fast, good-enough approximation for a hard problem.
  • As a first attempt, to check against a slower exact method on small inputs.

Avoid it when

  • You can't argue why the greedy choice is safe: test it against brute force or DP on small cases first.
  • Choices interact, as in knapsack with indivisible items: use dynamic programming.

Pitfalls

  • Assuming greedy is optimal without proof: coin change with unusual denominations is the classic trap.
  • Sorting by the wrong key: for interval scheduling, sorting by start time or by length both fail.
  • Ties that change the result if broken differently.

Alternatives

Dynamic programming

Choose it when you need a guaranteed optimum and greedy isn't proven correct.

Backtracking

Choose it when you need all solutions, or constraints make local choices unsafe.