Skip to the solution
MediumDSA16 min read

What is a greedy algorithm?

591 views

The problem

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, and functools.cmp_to_key when 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.

  • greedy

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

16 min read ยท 12 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonInterval scheduling: three greedy rules vs brute force
PythonGreedy coin change vs dynamic programming
PythonFractional vs 0/1 knapsack: same greedy, different verdict

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 81 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

How do you merge overlapping intervals?

Continue