Greedy Algorithm Interview Questions

How to approach greedy algorithm questions

A greedy algorithm builds a solution one step at a time, always taking the option that looks best right now and never going back to change an earlier choice. In interviews, a greedy solution often looks like a single pass through an array that keeps track of the best answer so far, which can turn an O(n²) brute-force solution into an O(n) one.

The hard part is knowing when greedy is safe. Before you commit, try to break your idea with a small counterexample, and be ready to explain why the locally best choice never rules out the best overall answer. If you find a counterexample, the problem probably needs dynamic programming instead.

A good way in: start from the brute-force solution, then ask what you'd need to remember as you walk through the input once so that you could drop the inner loop.

Interview Cake isn't just another question database. Each question below walks you through the problem step by step, with hints and explanations as you need them, just like a real interviewer.

Concepts to review

Quick reference: Big O cheat sheet

Greedy algorithm interview FAQ

What is a greedy algorithm?

An algorithm that builds a solution step by step, always making the choice that looks best at that moment without reconsidering earlier choices. It's fast and simple, but it only gives the right answer for problems where the locally best choices add up to the best overall answer.

How do I know if a greedy approach will work?

Try to find a small input where the greedy choice leads to a worse final answer. If you can't, try to argue that some optimal solution always includes the greedy choice. In an interview, testing a few tricky examples by hand is often the quickest check.

Can a greedy algorithm give the wrong answer?

Yes. Making change for 6 cents with coins worth 1, 3 and 4 cents, a greedy algorithm takes the biggest coin first and ends up with 4 + 1 + 1, three coins, but 3 + 3 needs only two. That's why it's worth testing a greedy idea on small cases before you code it.

What's the difference between greedy algorithms and dynamic programming?

A greedy algorithm commits to one choice at each step and never revisits it. Dynamic programming considers every choice at each step and combines the best answers to smaller subproblems, which is slower but correct even when the locally best choice turns out to be a mistake.

What are some common greedy algorithm interview questions?

Examples include finding the best time to buy and sell a stock, fitting the most non-overlapping meetings into a day, the jump game, and Huffman coding.
. . .