Question presented to candidate: "What is a greedy algorithm? How do you know when a greedy approach gives the optimal answer, and can you show one example where it works and one where it fails โ in Python?"
What a strong answer should cover:
- A one-sentence definition: build the answer step by step with the locally best choice and never undo a choice.
- The two conditions for correctness โ the greedy-choice property and optimal substructure โ and the exchange argument used to prove the first.
- A working example, typically interval scheduling by earliest finish time: sort, then one pass, O(n log n).
- A failing example with a concrete counterexample (coin change with
[1, 3, 4]and amount 6, or 0/1 knapsack), and that dynamic programming is the fix. - Python details:
sorted(..., key=lambda iv: (iv[1], iv[0]))with a tuple key for deterministic ties, Python's sort being stable, andfunctools.cmp_to_keywhen the natural order is a pairwise comparison. - Testing a greedy rule against a brute force on small inputs before trusting it.
Code / implementation expected: Optional โ a short Python greedy (interval scheduling or coin change) and its counterexample.