Greedy
A greedy algorithm makes the locally best choice and never revisits it. It is fast when you can prove that local choice is safe, and wrong when you cannot.
Detailed Explanation
Greedy is not a data structure. It is a proof obligation. At each step you pick the choice that looks best — earliest finish time, smallest denomination, highest ratio — and you do not backtrack. If that sequence is always optimal, you have an O(n log n) sort plus a linear scan instead of an exponential search or a DP table.
Classic cases that work: interval scheduling by earliest finish, Huffman codes, Dijkstra (greedy on distances with a proof), Kruskal / Prim for MSTs, activity selection. Classic cases that fail: coin change with arbitrary denominations (need DP), longest path, most packing problems. The failure mode is a counterexample, not a compiler error. Write the counterexample before you ship.
In Rust the implementation is usually: sort a Vec with the greedy key, then scan once, pushing into an answer. sort_unstable_by_key plus a for loop is the whole program more often than people expect. A BinaryHeap is greedy when you repeatedly take the current best remaining item (Huffman, Dijkstra, "always merge the two smallest").
Do not confuse greedy with "I used a heap". A heap can implement Dijkstra (correct) or a mistaken "always take the largest remaining number" for a problem that needs DP (incorrect). The heap is the priority queue. The proof is the algorithm.
When you reach for greedy: you have a proof or a well-known reduction. When you reach for DP: overlapping subproblems and no safe local choice. When you reach for brute force: n is tiny and a proof would take longer than the nested loop.
Code Examples
struct Interval {
start: i32,
end: i32,
}
fn max_non_overlapping(mut items: Vec<Interval>) -> usize {
items.sort_unstable_by_key(|i| i.end);
let mut count = 0;
let mut last_end = i32::MIN;
for i in items {
if i.start >= last_end {
count += 1;
last_end = i.end;
}
}
count
}
fn main() {
let items = vec![
Interval { start: 1, end: 3 },
Interval { start: 2, end: 5 },
Interval { start: 4, end: 7 },
];
println!("{}", max_non_overlapping(items)); // prints: 2
}Common Gotchas
A plausible greedy can be wrong
Coin systems that are not canonical need DP. Write a small counterexample before coding.
The sort key is the algorithm
Earliest finish, not earliest start, is what makes interval scheduling work. Sorting the wrong field is a silent wrong answer.
Heaps implement some greedy algorithms
They do not make a wrong choice right. Dijkstra's proof is why the heap version works.
Greedy plus backtracking is not greedy
If you undo, you are searching. Say so, and bound the search.