Skip to main content
Intermediate ~14 min read

Greedy Algorithms

Take the best local choice and never look back, fast and elegant when you can PROVE it works.

Prerequisites: Big O Notation & Time Complexity, Heaps & Priority Queues

A greedy algorithm makes the choice that looks best RIGHT NOW and never revisits it. No backtracking, no memo table, one pass, usually after a sort. That's the appeal: greedy solutions are short, fast (often O(n log n) dominated by the sort), and easy to implement. That's also the danger: greedy is only correct when local optimum ⇒ global optimum, and that's a THEOREM you must be able to argue, not an assumption you get to make.

The standard justification is the exchange argument: show that any optimal solution can be transformed into the greedy one without getting worse, so the greedy solution is at least as good. When that argument holds (interval scheduling: picking the earliest-finishing meeting never hurts), greedy is optimal. When it fails (coin change with coins {1, 3, 4}: greedy takes 4+1+1 = 3 coins for 6, but 3+3 = 2 coins), you need dynamic programming instead.

Classic greedy win: maximum non-overlapping intervals

intervals.js
// Attend the maximum number of meetings (one room).
// Greedy rule: always take the meeting that ENDS earliest.
function maxMeetings(intervals) {
  const sorted = [...intervals].sort((a, b) => a[1] - b[1]);  // by END time
  let count = 0;
  let lastEnd = -Infinity;
  for (const [start, end] of sorted) {
    if (start >= lastEnd) {       // compatible with everything chosen so far
      count++;
      lastEnd = end;              // commit, never un-choose
    }
  }
  return count;
}
// Why earliest-end? Any optimal schedule's FIRST meeting can be swapped
// for the earliest-ending one without blocking later meetings. Greedy stays optimal.

The greedy checklist

  1. 1

    Sort into a decision order

    Almost every greedy solution starts with a sort that makes "locally best" well-defined: by end time, by ratio, by deadline.

  2. 2

    Define the local rule

    One sentence: "take the earliest end / the largest ratio / the k smallest". If your rule needs a paragraph, it's probably DP.

  3. 3

    Commit without regret

    Greedy never revisits. If the solution structure requires un-choosing, it's backtracking or DP.

  4. 4

    Argue the exchange

    Can any optimal answer be rearranged to match your choice without loss? If yes, implement. If no, find a counterexample or switch to DP.

Check your understanding

  1. 1.Interval scheduling: why sort by END time rather than START time?
  2. 2.Coins {1, 3, 4}, amount 6, greedy by largest coin gives 3 coins. What does this counterexample prove?
  3. 3.Which situation signals 'use a heap' inside a greedy algorithm?

Finished reading?

Mark it complete to earn +50 XP. Progress stays in your browser.

Keep going