Greedy Algorithms

In short: A greedy algorithm builds a solution step by step, always making the choice that looks best right now. It's fast and simple, and for some problems (like Dijkstra's or Huffman coding) the local choices add up to a globally optimal answer, but not for all problems.

A greedy algorithm builds up a solution by choosing the option that looks the best at every step.

Say you're a cashier and need to give someone 67 cents (US) using as few coins as possible. How would you do it?

Whenever picking which coin to use, you'd take the highest-value coin you could. A quarter, another quarter, then a dime, a nickel, and finally two pennies. That's a greedy algorithm, because you're always greedily choosing the coin that covers the biggest portion of the remaining amount.

Some other places where a greedy algorithm gets you the best solution:

  • Trying to fit as many overlapping meetings as possible in a conference room? At each step, schedule the meeting that ends earliest.
  • Looking for a minimum spanning tree in a graph? At each step, greedily pick the cheapest edge that reaches a new vertex.

Careful: sometimes a greedy algorithm doesn't give you an optimal solution:

Validating that a greedy strategy always gets the best answer is tricky. Either prove that the answer produced by the greedy algorithm is as good as an optimal answer, or run through a rigorous set of test cases to convince your interviewer (and yourself) that it's correct.

Frequently Asked Questions

What is a greedy algorithm?

An algorithm that makes the locally optimal choice at each step, hoping those choices lead to a globally optimal solution.

When do greedy algorithms work?

When the problem has optimal substructure and the greedy-choice property, meaning a sequence of locally optimal choices yields a globally optimal result, as in Dijkstra's algorithm and Huffman coding.

What's the difference between greedy and dynamic programming?

Greedy commits to one choice at each step and never reconsiders; dynamic programming explores and combines overlapping subproblems, which is needed when greedy choices don't guarantee the optimum.

Last updated: June 17, 2026

. . .