Pattern

Greedy

Make the locally forced or locally best choice at each step, then prove — don't assume — that no later choice can beat it.

What it is

A greedy algorithm builds a solution by making one irreversible, locally-determined choice at a time — buy at the lowest price seen so far, keep the interval that ends earliest, cut the schedule at the first "peak" digit — and never revisits that choice. It works only when the problem has a structural guarantee that the locally best move is also part of some globally optimal solution. The technique itself is a one-pass or two-pass scan with O(1) or O(log n) extra bookkeeping per step; the hard part is never the loop, it's the argument for why the loop is allowed to stop looking back.

When it applies

Tells in the problem

The classic mistake

The mistake is coding the first greedy rule that seems plausible without checking it against an adversarial example, especially when a constraint is one-directional (a neighbor comparison, a single cooldown) but the real problem is symmetric or has a second direction. A single left-to-right pass that only enforces "bigger than my left neighbor gets more" silently breaks the mirrored right-side constraint, and a rule like "start where the local surplus is largest" can fail on inputs where the biggest local advantage still runs out of resources two steps later. It happens because the greedy's plausibility is easy to confirm on the example in the prompt and hard to break without deliberately constructing a case where an early strong choice causes a later failure. Before trusting a greedy, try to construct that adversarial case yourself, and if the constraint has two sides (left/right, before/after), ask whether one pass truly covers both or whether you need two.

Questions to start with

All 14 greedy questions

Problem statement, examples and hints are free on every page; the worked approach, solution and tests are in the company guides.

Free starter pack

13 must-tier questions with full solutions

Sign in with an email — no purchase — and read them in the full reader.

No password, no spam. One sign-in email; you can read the pack in the full reader.