Greedy
A greedy algorithm makes the choice that looks best right now and never retracts it. It is correct only when that local choice is safe for the global answer.
Detailed Explanation
Backtracking tries a choice, explores, and undoes. DP tries all useful subcombinations and keeps the best. Greedy picks once and moves on. That is faster — often O(n log n) for a sort plus a pass — and it is wrong unless you can say why a leftover better choice cannot exist.
The usual proof shapes: greedy choice property (there is an optimal solution that includes this pick) and optimal substructure (the rest of the problem is the same kind of problem). If you cannot sketch one of those, do not ship a greedy solution to a counting or min-cost problem.
Classic correct greedies:
- Interval scheduling: always take the remaining interval that finishes first.
- Huffman coding: merge the two lightest nodes.
- Dijkstra: pop the closest unsettled node (weights must be non-negative).
- Fractional knapsack: take value/weight density (the integer knapsack is DP).
Classic false greedies: coin systems that are not canonical (US coins work; some sets do not), "always take the largest task" for makespan, and most path-max problems on graphs with negative weights.
In JavaScript the implementation is often sort plus a loop, sometimes plus a heap. Comparators must match the greedy key (a.end - b.end). A heap greedy (Huffman, merging files) needs a structure you write yourself.
What it costs you: silent wrong answers. Greedy code is short and looks confident. Tests that only use the textbook instance will pass. Add an adversarial case: overlapping intervals that punish "longest first", coin amounts that punish "largest coin first".
Reach for greedy when a sort order makes later conflicts impossible, or when a standard theorem applies. Reach for DP when choices interact. Reach for backtracking when you must enumerate. If an interviewer asks "can you do better than DP?", greedy is the question they are asking — prove it or say no.
Code Examples
function maxMeetings(intervals) {
const sorted = [...intervals].sort((a, b) => a.end - b.end);
const picked = [];
let end = -Infinity;
for (const slot of sorted) {
if (slot.start >= end) {
picked.push(slot);
end = slot.end;
}
}
return picked;
}
const meetings = [
{ start: 1, end: 4 },
{ start: 3, end: 5 },
{ start: 0, end: 6 },
{ start: 5, end: 7 },
{ start: 8, end: 9 },
];
console.log(maxMeetings(meetings).map((m) => [m.start, m.end]));
// => [ [ 1, 4 ], [ 5, 7 ], [ 8, 9 ] ]function minCoinsCanonical(amount, coins) {
// Works for US coins; not for arbitrary sets.
const sorted = [...coins].sort((a, b) => b - a);
let left = amount;
let n = 0;
for (const c of sorted) {
n += Math.floor(left / c);
left %= c;
}
return left === 0 ? n : -1;
}
console.log(minCoinsCanonical(30, [1, 5, 10, 25])); // => 2Common Gotchas
Greedy is not a default for "minimum number"
coin change and knapsack are DP on general inputs.
The sort key is the algorithm
sorting by start instead of end in interval scheduling is a different, wrong greedy.
Dijkstra needs non-negative weights
negative edges break the "closest is done" claim. Use Bellman-Ford.
A passing sample is not a proof
write one sentence why the discarded choice cannot beat you.