Skip to content

greedy algorithm

A greedy algorithm is an algorithm that builds a solution one step at a time, always taking the option that looks best at that moment and never revisiting a choice once it’s made.

At each step, a fixed rule picks the locally best candidate, such as the cheapest edge in a graph, the largest coin, or the task that finishes earliest. The algorithm commits to that pick and moves on to the smaller problem that remains. Because it never backtracks or weighs whole alternatives against each other, a greedy approach is usually fast, and its running time is often dominated by an initial sort.

Local choices add up to a globally optimal answer only when a problem has two properties:

  • Greedy-choice property: Some optimal solution begins with the choice the greedy rule makes, so committing to it early never rules out the best answer.
  • Optimal substructure: An optimal solution to the whole problem contains an optimal solution to the subproblem left after each choice.

Several classic algorithms meet both conditions and are provably optimal. Prim’s algorithm and Kruskal’s algorithm build minimum spanning trees, Dijkstra’s algorithm finds shortest paths when no edge weight is negative, and Huffman coding builds optimal prefix codes. Scheduling the most non-overlapping tasks by always taking the one that ends earliest is another textbook case.

When the greedy-choice property fails, the strategy can return a poor answer. Making change for 6 with coins worth 1, 3, and 4 shows the problem. The greedy rule takes 4 and then two 1s for three coins, while two 3s need only two.

The widget below steps through the greedy rule for a few coin sets and compares its result with the fewest coins possible:

Interactive diagram — enable JavaScript to view.

Problems like this usually call for dynamic programming or exhaustive search instead. Greedy rules still serve as fast heuristics for hard problems, such as building a traveling salesman tour by always visiting the nearest unvisited city, accepting a result that may fall short of optimal.

Build a Maze Solver in Python Using Graphs

Tutorial

Build a Maze Solver in Python Using Graphs

In this step-by-step project, you'll build a maze solver in Python using graph algorithms from the NetworkX library. Along the way, you'll design a binary file format for the maze, represent it in an object-oriented way, and visualize the solution using scalable vector graphics (SVG).

intermediate projects

For additional information on related topics, take a look at the following resources:

Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.


By Martin Breuss • Updated Nov. 17, 2026