Greedy
Make the best-looking choice at each step and never undo it. Fast and short when it is correct, and wrong in quiet ways when it is not, so the proof matters as much as the code.
Overview
A greedy algorithm builds an answer one step at a time. At each step it takes the choice that looks best right now, by one fixed rule, and never goes back to change it. You already know the idea: a cashier making change hands over the largest coin that fits, then the largest coin that fits what is left, and so on until the amount is paid. Nobody plans the whole pile of coins in advance, and no choice is ever taken back.
That is why greedy code is short and fast: usually one sort and one pass, O(n log n) time. The catch is that the rule is only sometimes right. Greedy problems test two skills: picking the right rule, and explaining why it cannot miss a better answer. This chapter builds both, and it ends with a coin set where the cashier's rule gives the wrong answer.
Each section below follows the same shape: the rule first, then the rule on a small example, then the trap to avoid.
The shape of a greedy solution
The rule: most greedy solutions are built from the same four parts, and all the thinking goes into two of them, the sort key and the fit test. Sort the items by the key and take them one at a time; keep an item that passes the fit test and update the state, and skip one that fails for good.
Take a classic problem: one meeting room, a list of meetings, and the goal of fitting in as many meetings as possible.
- The key sets the order in which you look at the items. For meetings, it is the end time, earliest first.
- The state is the one small thing you remember between steps. Here it is the end time of the last meeting you kept.
- The fit test decides whether to keep the next item. A meeting fits if it starts at or after that end time.
- The answer is what you return: how many meetings you kept.
Every item is looked at once, in sorted order, and no decision is revisited.
Sign up free to read the full topic
More Coding & DSA topics
Start free on Cariara · Coding problems · System design studio