Patterns

Greedy Algorithm Patterns for LeetCode Interviews

Greedy algorithms are deceptively simple — knowing when greedy works (and when it doesn't) is the real interview skill that separates good candidates from great ones.

10 min read|

Greedy algorithms: simple idea, tricky to know when they work

The patterns that separate greedy from DP in interviews

Greedy Looks Easy Until You Pick the Wrong Problem

Greedy algorithms have a reputation for being the easiest algorithmic strategy. Pick the locally optimal choice at each step, and you end up with the globally optimal solution. It sounds almost too good to be true — and for many problems, it is. The real interview skill is not implementing a greedy algorithm; it is knowing when greedy actually works.

Every experienced interviewer has watched a candidate confidently apply a greedy approach to a problem that requires dynamic programming, only to realize halfway through that their solution produces wrong answers. The coin change problem, the longest increasing subsequence, the knapsack — all of these tempt you with a greedy approach that falls apart on edge cases.

This guide covers the greedy algorithm LeetCode patterns you need to recognize, the classic problems where greedy shines, and the framework for deciding whether a greedy approach is correct before you commit to it. If you can answer "why is greedy correct here?" in an interview, you are already ahead of most candidates.

What Makes a Problem Greedy?

A problem is solvable by a greedy algorithm when it has two properties: the greedy choice property and optimal substructure. The greedy choice property means that making the locally optimal choice at each step leads to a globally optimal solution. Optimal substructure means the optimal solution to the problem contains optimal solutions to its subproblems.

The key difference between greedy and dynamic programming is backtracking. In DP, you explore multiple choices and combine their results. In greedy, you make one choice and never look back. This is why greedy algorithms are typically O(n) or O(n log n) while DP solutions can be O(n^2) or worse — you are doing less work because you are making fewer decisions.

How do you know if greedy works? Ask yourself: if I make the best local choice right now, can any future decision undo that optimality? If the answer is no, greedy works. If there is even one counterexample where a locally optimal choice leads to a globally suboptimal result, you need DP or another approach.

  • Greedy choice property: the locally optimal choice is part of the globally optimal solution
  • Optimal substructure: solving the remaining subproblem optimally gives you the full optimal solution
  • No backtracking needed: once you make a choice, you never need to reconsider it
  • Exchange argument: you can often prove greedy correctness by showing that swapping any non-greedy choice for the greedy one never makes things worse

Classic Greedy Algorithm LeetCode Problems

The best way to build greedy intuition is to study the problems where greedy is clearly correct. These classic problems appear frequently in coding interviews and each one teaches a different greedy pattern.

Jump Game (#55) asks whether you can reach the last index of an array where each element represents your maximum jump length. The greedy approach tracks the farthest reachable index as you scan left to right. If your current index ever exceeds the farthest reachable position, return false. This works because reaching an intermediate position always gives you at least as many options as skipping it.

Jump Game II (#45) extends the idea — now you need the minimum number of jumps. The greedy insight is to always jump to the position that maximizes your reach from the next jump. Think of it as BFS by levels: each "level" is one jump, and you greedily extend the boundary of the next level.

Gas Station (#134) asks you to find the starting gas station on a circular route where you can complete the full circuit. The greedy approach is elegant: if the total gas is greater than or equal to the total cost, a solution exists. To find the starting point, track your running surplus and reset your start position whenever the surplus goes negative.

Best Time to Buy and Sell Stock (#121) is perhaps the simplest greedy problem. Track the minimum price seen so far and the maximum profit at each step. You are greedily choosing the best buying point as you scan forward.

  • Jump Game (#55): track farthest reachable index — O(n) time, O(1) space
  • Jump Game II (#45): BFS-style level expansion — O(n) time, O(1) space
  • Gas Station (#134): running surplus with start reset — O(n) time, O(1) space
  • Best Time to Buy and Sell Stock (#121): track min price and max profit — O(n) time, O(1) space
💡

Pro Tip

If a problem asks for 'minimum number of steps' or 'maximum profit' and you can prove the locally optimal choice is globally optimal, it's greedy.

Interval Scheduling Problems — The Most Common Greedy Category

If there is one greedy subcategory you must master for interviews, it is interval scheduling. These problems come up constantly, and they all share a common pattern: sort the intervals, then make greedy choices about which ones to keep or merge.

Non-overlapping Intervals (#435) asks for the minimum number of intervals to remove so that the rest do not overlap. The greedy strategy is to sort by end time, then greedily keep intervals that do not conflict with the last kept interval. Why sort by end time? Because ending earlier leaves more room for future intervals — this is the activity selection problem from textbooks.

Meeting Rooms II (#253) asks for the minimum number of conference rooms needed. Sort meetings by start time, then use a min-heap to track the earliest ending meeting in each room. When a new meeting starts, if it starts after the earliest-ending room is free, reuse that room. Otherwise, allocate a new room. The greedy choice is always reusing the room that frees up earliest.

Merge Intervals (#56) is the most straightforward interval problem. Sort by start time, then greedily merge overlapping intervals by extending the end time. The key insight is that after sorting, you only need to compare each interval with the last merged interval.

  • Non-overlapping Intervals (#435): sort by end time, greedily keep non-conflicting — O(n log n)
  • Meeting Rooms II (#253): sort by start time, min-heap for room tracking — O(n log n)
  • Merge Intervals (#56): sort by start time, extend overlapping end times — O(n log n)
  • Activity Selection: the textbook foundation — always pick the activity that finishes earliest

Greedy vs Dynamic Programming — When Greedy Fails

The hardest part of greedy algorithm interview questions is not the implementation — it is recognizing whether greedy is even correct. Many problems look greedy on the surface but require dynamic programming because the locally optimal choice is not globally optimal.

The 0/1 Knapsack problem is the classic example. Greedy says "always pick the item with the best value-to-weight ratio," but this fails when items cannot be divided. A heavy, high-value item might block two lighter items that together provide more value. You need DP to explore both taking and not taking each item.

Longest Increasing Subsequence also tempts a greedy approach: always extend with the smallest possible next element. While this greedy idea does help with the O(n log n) patience sorting approach, the naive greedy of "always pick the next larger number" fails because it does not account for future possibilities.

Here is a practical decision framework for interviews: if the problem has overlapping subproblems where choices interact with each other, use DP. If each choice is independent and provably optimal regardless of future choices, use greedy. When in doubt, try to find a counterexample for the greedy approach — it usually takes less than a minute.

  • Greedy works: each choice is independent, locally optimal equals globally optimal
  • DP required: choices have dependencies, you need to explore multiple paths
  • Quick test: can you find a small counterexample where greedy gives the wrong answer?
  • Interview tip: if the problem asks for "all possible" or "count of ways," it is almost never greedy
⚠️

Watch Out

The coin change problem looks greedy but isn't — using the largest denomination first fails for denominations like [1, 3, 4]. This is the classic greedy vs DP trap.

Common Greedy Mistakes That Cost Interview Points

The most dangerous greedy mistake is assuming greedy works without verifying it. In an interview, stating "I will use a greedy approach" without explaining why it is correct shows a gap in problem-solving rigor. Always articulate the greedy choice property, even if it is just one sentence.

Another common mistake is confusing local optimality with global optimality. Just because choosing the largest element first works for one test case does not mean it works for all inputs. The coin change problem is a perfect example: using denominations [1, 3, 4] and making change for 6, the greedy approach picks 4 + 1 + 1 = three coins, but the optimal solution is 3 + 3 = two coins.

A subtler mistake is choosing the wrong greedy criterion. In interval scheduling, sorting by start time instead of end time gives the wrong answer for non-overlapping intervals. The difference between a correct and incorrect greedy solution often comes down to which metric you optimize at each step.

Finally, forgetting to handle edge cases after establishing the greedy approach is a common interview pitfall. Empty arrays, single-element inputs, and all-identical values often break greedy solutions that work perfectly on typical inputs. Always test your greedy approach against degenerate cases before coding.

Building Greedy Intuition — Practice Strategy

Greedy intuition is not something you develop by reading about it — you build it by solving problems and recognizing patterns. The good news is that the greedy problem space is smaller than DP, so targeted practice goes a long way.

Start with the classic problems covered in this guide: Jump Game, Gas Station, and the interval scheduling family. These are the highest-frequency greedy problems in real interviews. Once you can solve them confidently, move to problems like Task Scheduler (#621), Partition Labels (#763), and Candy (#135) for more advanced greedy patterns.

For each problem, practice the full interview loop: identify why greedy works, articulate the greedy choice property, implement the solution, and verify with edge cases. YeetCode flashcards are built around exactly this flow — each card tests whether you can recall the pattern, the key insight, and the proof of correctness without looking at the solution.

The ultimate test of your greedy algorithm mastery is speed of recognition. When you see a new problem, can you decide within two minutes whether greedy applies? That recognition speed comes from spaced repetition — reviewing patterns at increasing intervals so they stay fresh in your working memory. Combine targeted practice with regular review, and greedy problems will become some of the fastest solves in your interview toolkit.

ℹ️

Key Insight

Interval problems are the most common greedy category in interviews — sorting by end time is almost always the key insight.

Ready to master algorithm patterns?

YeetCode flashcards help you build pattern recognition through active recall and spaced repetition.

Start practicing now