Browse curriculum

Greedy Algorithms

The Greedy Algorithms Pattern

Take the best-looking option at each step and never reconsider. Greedy produces short, fast solutions — but only for problems where the locally optimal choice is provably globally optimal, which is the part that has to be argued rather than assumed.

4

Interactive problems

1

Free to open

Recognise

How do you recognise a greedy algorithms problem?

The problem asks for a maximum or minimum and there is a natural ordering that makes one choice obviously safest — earliest finishing time, largest value first. If a counterexample comes to mind quickly, the problem is dynamic programming instead.

Complexity

What is the time complexity of the greedy algorithms pattern?

Typically O(n log n) for the sort plus O(n) for a single pass.

Problems

Greedy Algorithms practice problems

Each problem pairs a worked explanation with an interactive visualizer you step through yourself, plus the implementation in JavaScript, Python, Java and C++.

Complexity

Greedy Algorithms problems by difficulty and complexity

The difficulty, running time and extra space of every greedy algorithms solution on this page, as each lesson derives them.

LessonDifficultyBestAverageWorstSpace
Introduction to Greedy AlgorithmsEasyΩ(k log k)Θ(k log k)O(k log k)O(1)
Best Time to Buy and Sell StockEasyΩ(n)Θ(n)O(n)O(1)
Gas StationMediumΩ(n)Θ(n)O(n)O(1)
Jump GameMediumΩ(1)Θ(n)O(n)O(1)
Curriculum

The underlying technique is covered from first principles in the greedy algorithms lesson in the DSA visualizer curriculum. Greedy Algorithms is one of the 17 coding interview patterns, and its problems also appear in the DSA 75 interview sprint.

Directory

Every other coding interview pattern