Greedy Algorithms

Make the locally best choice at every step — when that provably works, how to prove it, and when it fails.

Intermediate 3 min readLesson 7 of 18 Interview Q&A

A greedy algorithm builds a solution step by step, always taking the choice that looks best right now, and never reconsidering. When it works, it's usually the simplest and fastest solution — often just "sort, then scan".

The catch: greedy is correct only when the problem has

  1. Greedy-choice property — some optimal solution starts with the greedy choice, and
  2. Optimal substructure — after making it, what remains is a smaller instance of the same problem.

When greedy fails

Coin change with coins {1, 3, 4} and target 6: greedy takes 4 + 1 + 1 (3 coins), but 3 + 3 (2 coins) is optimal. For arbitrary coin systems you need DP. (For "canonical" systems like US coins, greedy happens to be optimal.)

Proving greedy correct: the exchange argument

Take any optimal solution that differs from the greedy one. Show you can swap in the greedy choice without making it worse. Repeating the swap transforms the optimal solution into the greedy one, so greedy is optimal too.

Classic 1: activity selection (interval scheduling)

Choose the maximum number of non-overlapping meetings. Greedy rule: always pick the meeting that ends earliest. It leaves the most room for the rest (exchange argument: replacing the optimum's first meeting with the earliest-ending one can't cause a conflict).

ABCDE02345678911
Sorted by end time, greedy keeps A, C, E (green) and skips overlapping B and D.
int maxMeetings(int[][] intervals) {
    Arrays.sort(intervals, (a, b) -> Integer.compare(a[1], b[1]));  // by end time
    int count = 0, lastEnd = Integer.MIN_VALUE;
    for (int[] iv : intervals) {
        if (iv[0] >= lastEnd) {        // doesn't overlap the last chosen one
            count++;
            lastEnd = iv[1];
        }
    }
    return count;
}
// "Minimum removals to make intervals non-overlapping" = n - maxMeetings

Classic 2: jump game

Can you reach the last index if a[i] is the max jump from i? Track the farthest reachable index while scanning; if you ever stand beyond it, you're stuck.

boolean canJump(int[] a) {
    int far = 0;
    for (int i = 0; i < a.length; i++) {
        if (i > far) return false;
        far = Math.max(far, i + a[i]);
    }
    return true;
}

Classic 3: Huffman coding

Build an optimal prefix-free code for compression: repeatedly merge the two least frequent symbols into a new node (using a min-heap). Frequent symbols end up near the root with short codes. Used inside DEFLATE (zip, gzip, PNG) and JPEG.

a:45c:12b:1325f:5e:914d:163055100
Huffman tree: 'a' (most frequent) gets code 0; 'f' gets 1100.

More greedy algorithms you'll meet

ProblemGreedy ruleLesson
Fractional knapsackHighest value/weight first (0/1 knapsack needs DP)Knapsack DP
Minimum spanning treeCheapest safe edge (Kruskal) / closest vertex (Prim)MST
DijkstraClosest unvisited vertexShortest paths
Gas stationRestart after a negative running tankGreedy pattern
Task schedulerSchedule the most frequent task firstGreedy pattern
Minimum platforms / meeting roomsSweep sorted start/end eventsMerge intervals
Key takeaways
  • Greedy takes the locally best choice and never backtracks.
  • It's correct only with the greedy-choice property and optimal substructure — prove it (exchange argument) or find a counterexample.
  • Most greedy solutions are "sort by the right key, then scan": O(n log n).
  • If greedy fails, the problem usually needs dynamic programming.
Interview questions
QMinimum number of arrows to burst all balloons (intervals).medium

Sort by end. Shoot an arrow at the first balloon's end; it bursts every balloon starting at or before that point. Move to the next balloon starting after it and repeat. Same proof as activity selection.

QWhy does greedy work for fractional knapsack but not 0/1 knapsack?medium

With fractions, you can always fill the remaining capacity with the best value-per-weight item, so the exchange argument holds. In 0/1 knapsack an item is all-or-nothing: taking the best-ratio item can waste capacity that a different combination would fill better. That requires DP.