Skip to main content

LeetCode Patterns

Greedy Pattern

The Greedy pattern builds an answer one step at a time by always taking the locally optimal choice, never reconsidering past decisions. It works when the problem has the greedy-choice property and optimal substructure, letting a single linear pass replace an exponential search. Typical runtime is O(n) or O(n log n) when sorting first, with O(1) extra space.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Complexity

Time
O(n log n)
Space
O(1)

When to use Greedy

  • The problem asks for the minimum or maximum of something that can be assembled from local choices (jumps, intervals, swaps).
  • You can prove a swap argument: any optimal solution can be transformed into the greedy one without making it worse.
  • Sorting the input by a meaningful key (deadline, end time, profit-to-weight ratio) makes the locally best choice obvious.
  • The problem says 'find any valid', 'is it possible', or 'minimum number of operations' rather than 'count all ways'.
  • Dynamic programming would solve it but the state-transition collapses to a single tracked variable (current reach, last end, running max).

Template

function greedy(items) {
  items.sort((a, b) => a.key - b.key);
  let result = 0;
  let frontier = 0;
  for (const item of items) {
    if (item.start > frontier) {
      return -1;
    }
    if (canTakeLocallyOptimal(item, frontier)) {
      result++;
      frontier = item.end;
    }
  }
  return result;
}

Example LeetCode problems

#ProblemDifficultyFrequency
55Jump Gamemediumfoundational
45Jump Game IImediumfrequently asked
134Gas Stationmediumcompany favorite
621Task Schedulermediumcompany favorite
763Partition Labelsmediumfrequently asked
455Assign Cookieseasyfoundational
122Best Time to Buy and Sell Stock IImediumclassic
435Non-overlapping Intervalsmediumfrequently asked

Common mistakes

  • Applying greedy when the problem actually requires dynamic programming — failing to prove the greedy-choice property leads to subtle counterexamples on edge cases.
  • Sorting by the wrong key. In Non-overlapping Intervals, sorting by start time misses optimal selections; sorting by end time is the canonical move.
  • Resetting the running frontier (Gas Station's tank, Jump Game's reach) at the wrong moment, off-by-one on the index where you restart.
  • Forgetting to short-circuit when the greedy step fails — Jump Game returns false the instant the frontier can't reach the next index.
  • Greedy on Task Scheduler without using a max-heap or a frequency-count formula, causing TLE on large inputs.

Frequently asked questions

When should I use Greedy vs Dynamic Programming?

Use greedy when you can prove a swap argument or exchange argument shows local choices stay optimal. Use DP when the optimal answer at step n depends on multiple past states that can't be collapsed. A safe heuristic: if you can describe the algorithm as 'sort then take the best one at each step', greedy probably works.

How do I prove a greedy algorithm is correct in an interview?

State the greedy choice explicitly, then argue by exchange: assume an optimal solution disagrees with the greedy choice at the first step, swap that step with the greedy one, and show the resulting solution is no worse. If the swap always succeeds, greedy is optimal.

Why does Gas Station use a single pass instead of trying every starting station?

If the total gas is at least the total cost, a valid start exists. The greedy insight is that whenever the running tank goes negative at station i, no station from the previous candidate up to i can be the answer, so you can skip ahead to i+1 and reset the tank to zero.

What is the difference between greedy and a sweep-line algorithm?

Sweep-line is one common implementation of greedy on interval problems: sort events by time, then process them in order while maintaining a counter or heap. Greedy is the broader strategy; sweep-line is a specific data structure pattern that supports it.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill the Greedy pattern under real interview conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →