Greedy algorithms

Make the best-looking choice now, never take it back, and move on. When you can show that choice is always safe, one pass gives the best answer, often right after a sort.

3 examples17 to practiceRead · 5 min
The idea

One safe choice at a time, never undone

A greedy algorithm builds its answer one step at a time. At each step it takes the option that looks best right now, the greedy choice, and never revisits it. There is no search over alternatives and no backtracking, so it is usually a sort followed by a single O(n) pass.

The catch is that "looks best now" is often wrong. Paying 6 with coins 1, 3 and 4, taking the largest coin first gives 4 + 1 + 1, three coins, while 3 + 3 needs two. So a greedy solution comes with a reason it is safe. The usual one is an exchange argument: take any best answer that differs from yours at the first choice, swap your greedy choice into it, and show the result is no worse. If that always works, some best answer starts with your choice, and the same reasoning covers every step after it.

The rule

Use a greedy algorithm only when you can say why the greedy choice can always be part of a best answer. If you can't, test it on a small counterexample before trusting it.

Spotting it

Sorting reveals an order where the cheapest or tightest item goes first

Match items from two lists, as many pairs as possible

Sort both; pair the smallest item that works with the smallest that needs it

"Can you reach the end?" or "fewest steps" with jump lengths

Track only the farthest point you can reach so far

Choose the most non-overlapping events

Sort by end time; always keep the one that ends first

Each item must satisfy rules about its neighbors

Satisfy one side in a left-to-right pass, the other in a right-to-left pass

A small counterexample beats the obvious rule

Not greedy: try dynamic programming instead

Basic

Give each cookie to the least greedy child it can satisfy

Each child needs a cookie of at least a certain size, and each cookie goes to one child at most. Sort both lists. Take the cookies from smallest up: if a cookie is big enough for the least demanding child still waiting, give it to that child. If it isn't, no one else can use it either, since everyone left needs more, so skip it.

The exchange argument: in any best answer, the smallest useful cookie could be handed to the least demanding child instead, and no child loses out. So the greedy pairing is as good as any.

Medium

Keep only the farthest cell you can reach

Each cell holds the longest jump you may take from it. Can you get from the first cell to the last? Trying every sequence of jumps explodes. The greedy view needs one number: the farthest cell reachable so far. Every cell up to it is reachable too, so walk left to right, stretching that number. If you ever stand past it, you are stuck.

The zeros are not traps as long as an earlier cell jumps over them. The greedy choice here is not a jump at all: it is the decision to remember only the reach, which is all that matters for the question.

Hard

Two passes, each fixing one side

Children stand in a row with ratings. Each gets at least one candy, and a child rated higher than a neighbor must get more than that neighbor. Find the fewest candies. One pass can't see both neighbors at once, so split the rule: a left-to-right pass makes every child beat a lower-rated left neighbor, then a right-to-left pass fixes the right neighbors, keeping the larger of the two counts so the first pass is not undone.

Each count is the smallest that satisfies its rule, and taking the larger of the two satisfies both, so no child gets more than necessary. Two O(n) passes in all.

The template

Sort, then take or skip in one pass

  1. 1items ← sorted by the key that makes the greedy choice come first
  2. 2answer ← empty
  3. 3for each item in items
  4. 4 if item can be added without breaking a rule
  5. 5 add item to answer
  6. 6 else
  7. 7 skip item
  8. 8return answer

Before writing it, name the key and say why the item that comes first under it is safe to take. Most greedy bugs are a wrong key: by start time instead of end time, by size instead of size per unit.

Traps

Where greedy solutions go wrong

Greedy that only looks right

Coins 1, 3 and 4 for 6: largest first gives three coins, the best is two. When a small counterexample breaks the rule, the problem usually needs dynamic programming.

The wrong sort key

For the most non-overlapping events, sorting by start time or by length fails; sorting by end time works. Test the key on three or four hand-made cases.

One pass for a two-sided rule

A rule about both neighbors needs two passes, or a careful argument that one is enough.

Changing an earlier choice

If the solution needs to go back and change earlier choices, it is not greedy any more: it is search, and its cost is no longer one pass.

Check yourself

3 questions

1. Paying 6 with coins 1, 3 and 4, what does "largest coin first" give?
2. To choose the most events that don't overlap, how do you sort them?
3. What does an exchange argument show?
Takeaways

Remember this

  • A greedy algorithm takes the best-looking choice at each step and never revisits it: usually a sort and one pass.
  • Trust it only with a reason, usually an exchange argument; a small counterexample, like coins 1, 3 and 4 for 6, means dynamic programming instead.
  • Most greedy bugs are a wrong sort key: name the key and say why the item that comes first under it is safe to take.
Practice

Now solve some yourself

Only this topic 0 of 11 solved

  1. Easy
    Make change at a lemonade stand
    Greedy algorithms
  2. Easy
    Fewest taxis for groups of up to four
    Greedy algorithms
  3. Easy
    Fewest notes to pay an amount
    Greedy algorithms
  4. Easy
    Load a truck with the most units
    Greedy algorithms
  5. Easy
    Flip signs k times for the largest sum
    Greedy algorithms
  6. Medium
    Profit from every rising day
    Greedy algorithms
  7. Medium
    Fewest jumps to the last cell
    Greedy algorithms
  8. Medium
    Where to start a trip around a fuel loop
    Greedy algorithms
  9. Medium
    Send people to two cities at the lowest cost
    Greedy algorithms
  10. Medium
    Rebuild a queue from heights and counts
    Greedy algorithms
  11. Hard
    Fewest numbers to add so every sum is possible
    Greedy algorithms

Mixed with topics you have practiced 0 unlocked

    6 more once you have practiced Basic sorting, Hash tables & maps, Heaps & priority queues, Merge intervals. Play one of its examples to the end and solve one of its problems to unlock them.

    Problems open on their own sites (LeetCode, Codeforces, CodeChef, AtCoder, CSES) in a new tab. Tick Solved when you get it accepted there; your ticks decide which mixed problems open next.

    Next

    Dynamic programming: basics

    Continue