Greedy
A greedy algorithm builds a solution by always taking the choice that looks best right now. It is fast when a proof says those local choices produce a global optimum, and wrong when they do not.
Detailed Explanation
Greedy is tempting because the loop is short. Sort the jobs by end time and pick the next one that fits. Always take the largest coin. Always merge the two shortest files. Sometimes that is optimal. Sometimes it is a counterexample away from failure.
The work is the proof, not the code. Exchange arguments ("any optimal solution can be rewritten to include my first pick") and greedy-stays-ahead arguments are the usual tools. If you cannot sketch a proof or cite a known problem (interval scheduling, Huffman, Dijkstra, Kruskal), do not ship a greedy as correct.
Counterexamples are cheap to try. Coin change with denominations 1, 3, 4 and amount 6: greedy 4+1+1 loses to 3+3. 0-1 knapsack: highest value-density first can lose to a less dense item that fills the bag better. When greedy fails, DP or search is the next stop.
Implementation is usually: sort by a key, then scan once, maintaining a small amount of state (last end time, remaining capacity). That is O(n log n) from the sort. Dijkstra is greedy plus a heap. Kruskal is greedy plus union-find.
Greedy is also a heuristic. A "good enough" load balancer or a game AI may use a greedy choice without a proof. Call that a heuristic in the comment so the next reader does not treat it as a theorem.
Code Examples
def schedule(intervals: list[tuple[int, int]]) -> list[tuple[int, int]]:
"""Maximum number of non-overlapping intervals. Greedy by end time."""
chosen = []
end = float("-inf")
for start, stop in sorted(intervals, key=lambda iv: iv[1]):
if start >= end:
chosen.append((start, stop))
end = stop
return chosen
print(schedule([(1, 3), (2, 4), (3, 5)])) # [(1, 3), (3, 5)]# Greedy coin change is optimal for canonical systems such as US cents.
def coins(cents: int) -> list[int]:
out = []
for piece in (25, 10, 5, 1):
n, cents = divmod(cents, piece)
out.extend([piece] * n)
return out
print(coins(41)) # [25, 10, 5, 1]Common Gotchas
"It worked on the sample" is not a proof
try a known counterexample family before you call it greedy-correct.
The sort key is the algorithm
sorting by start time instead of end time breaks interval scheduling. Write why the key is that field.
Greedy + wrong structure
"always pick the smallest edge" without union-find is not Kruskal; you will add cycles.
Dijkstra is greedy
the proof depends on non-negative weights. Negative edges need Bellman-Ford.