Command Palette

Search for a command to run...

Module 33

Greedy Algorithms

Make the best local choice and never look back, but only after proving it's safe: exchange arguments, reach tracking, resets, two passes and sorting tricks.

Intermediate 3 lessons 10 problems ~40 min of lessons

A greedy algorithm builds the answer one step at a time, always taking the choice that looks best right now, and never reconsiders. When it works, it's usually the simplest and fastest solution. When it doesn't, it's confidently wrong, so the real skill is knowing why a greedy choice is safe.

This module teaches the two standard proofs (exchange argument and "stays ahead"), shows a case where greedy fails and DP is needed, and practises the common greedy shapes: matching sorted lists, tracking the farthest reach, resetting a start point, two-pass constraints, sorting by a clever key, and building groups from the smallest element.

Best after: Sorting and Divide & Conquer

Part 1

Learn the ideas

Part 2

Solve the problems

In order of difficulty. Each one shows the pattern it teaches.

  1. Exchange argument: give each child the smallest cookie that satisfies them.

  2. Track the farthest reachable index in one pass.

  3. Implicit BFS levels: each range of reachable indices costs one jump.

  4. Reset the start after any failing stretch; a non-negative total guarantees success.

  5. Two passes for constraints from both neighbours.

  6. Extend the current part to the last occurrence of every letter inside it.

  7. Sorting by a clever key: place tall people first, then insert shorter ones at their index.

  8. Pair the heaviest person with the lightest if they fit; otherwise the heaviest goes alone.

  9. With unlimited transactions, collect every upward step.

  10. The smallest remaining card must start a group, so build groups from it.