Browse curriculum

Greedy Algorithms

Greedy Algorithms Interview Questions: 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. Below are the greedy algorithms interview questions from LeetCode, each with a step-by-step visual solution.

17

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 interview questions: 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)
Kids With the Greatest Number of CandiesEasyΩ(n)Θ(n)O(n)O(1)
Can Place FlowersEasyΩ(n)Θ(n)O(n)O(1)
Dota2 SenateMediumΩ(n)Θ(n)O(n)O(n)
Best Time to Buy and Sell StockEasyΩ(n)Θ(n)O(n)O(1)
Best Time to Buy and Sell Stock IIMediumΩ(n)Θ(n)O(n)O(1)
Increasing Triplet SubsequenceMediumΩ(1)Θ(n)O(n)O(1)
Gas StationMediumΩ(n)Θ(n)O(n)O(1)
Jump GameMediumΩ(1)Θ(n)O(n)O(1)
Jump Game IIMediumΩ(n)Θ(n)O(n)O(1)
Task SchedulerMediumΩ(n)Θ(n)O(n)O(1)
Partition LabelsMediumΩ(n)Θ(n)O(n)O(1)
Valid Parenthesis StringMediumΩ(1)Θ(n)O(n)O(1)
Hand of StraightsMediumΩ(1)Θ(n log n)O(n log n)O(n)
Merge Triplets to Form Target TripletMediumΩ(n)Θ(n)O(n)O(1)
Integer to RomanMediumΩ(1)Θ(1)O(1)O(1)
CandyHardΩ(n)Θ(n)O(n)O(n)
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 18 coding interview patterns, and its problems also appear in the DSA 75 interview sprint.

Directory

Every other coding interview pattern