Famous puzzles that keep showing up as contest problems or as the core of one. Each comes with its answer, the technique, and the general lesson.

Problems, not algorithms

These are questions whose answers happen to be famous — distinct from 🐬 Named Algorithms, which are methods. The full catalogue of named classic problems lives in 🐬 Classic Problems; every puzzle with an algorithmic core and its own dense note lives in 25. Puzzles.

Josephus problem

people in a circle; every -th is eliminated. With 0-indexed survivor position :

ll josephus(ll n, ll k) {                 // O(n)
    ll r = 0;
    for (ll i = 2; i <= n; i++) r = (r + k) % i;
    return r;
}
ll josephusFast(ll n, ll k) {             // O(k log n), for huge n and small k
    if (n == 1) return 0;
    if (k == 1) return n - 1;
    if (k > n) return (josephusFast(n - 1, k) + k) % n;
    ll c = n / k, r = josephusFast(n - c, k) - n % k;
    return r < 0 ? r + n : r + r / (k - 1);
}
  • : write in binary and rotate the leading 1 to the end, so the 1-indexed survivor is (proof below).
  • Elimination order: keep the survivors in a Fenwick tree and find the -th remaining by BIT descent, ; or use an order-statistics tree.
  • Lesson: when a recurrence adds a constant modulo a growing bound, batch the steps that don’t wrap. josephusFast above is this batching: each “wrap” of the modulus roughly multiplies the working index by , so only wraps occur before the index shrinks to 1.
  • Named for Flavius Josephus, who (per his own account of the Jewish–Roman war) survived a forced lottery-style elimination among trapped companions by working out where the safe positions were.

Tower of Hanoi

moves, and that’s optimal. Move (1-indexed) moves disk — exactly a Gray code: the bit that changes from to is , and each disk’s position is one bit of it. Small disks cycle in a fixed direction (ACB for odd ). Reve’s puzzle with 4 pegs: the Frame-Stewart algorithm moves disks aside with 4 pegs, the rest with 3, minimising over ; it uses about moves. The state graph of disks is the Sierpinski graph (diameter ), and BFS on it handles any start and target configuration — the shortest path between two arbitrary configurations is computable in by a greedy recursion, but is not always ; that is only the corner-to-corner distance. The ctz fact generalises: whenever a recursive process splits as and produces a sequence, that sequence usually has a description in terms of the binary expansion of the step index. Full derivation and tested code: Tower of Hanoi.

Water jugs

Capacities ; measure . Possible iff and (Bézout — the same fact that governs linear Diophantine equations and the Frobenius coin problem). Construct by repeatedly filling and pouring into (emptying when full), which walks through . For the minimum number of operations, BFS over states, . The famous Die Hard instance: ; since , it’s solvable.

Lesson: whenever a puzzle asks for the minimum number of operations, it is BFS on an implicit graph — the only real work is defining the state and the neighbour function:

ProblemStateMoves
water jugs litresfill, empty, pour
15-puzzleboard configurationslide a tile
wolf, goat, cabbagewho is on which bankcross with item
missionaries and cannibalscounts on each bankcross with 1-2 people
Rubik’s cubecube stateface turn
word laddera wordchange one letter
coin/token puzzlespositionslegal move
lock combinationscurrent coderotate a dial

For very large state spaces, bidirectional BFS halves the exponent.

Variants: with 3+ jugs the gcd condition generalises to the gcd of all capacities; jugs with markings just add more moves, still BFS; minimising the water used (rather than the number of pours) is Dijkstra with pour amounts as edge weights; measuring in one specific jug restricts the goal test. Full derivation and tested code: Water Jug.

Wolf, goat, cabbage and missionaries

States are subsets on each bank plus the boat side (16 states for the 4-item version); BFS finds the 7-crossing solution and proves it optimal. Missionaries and cannibals (3+3, boat of 2, 32 states) needs 11 crossings; the 4-and-4 version with the same 2-person boat is unsolvable, which BFS discovers immediately and is tedious to argue by hand. Lesson: encode the state, encode the forbidden states, BFS.

When the state space is too large for plain BFS: a hash set or bitset of visited states scales to ; bidirectional BFS to ; beyond that, A*/IDA* with a good heuristic, or pattern databases. If the state has symmetries (interchangeable items, reflections), canonicalising each state before hashing can shrink the search by a large constant factor. Tested code: Wolf, Goat, Cabbage.

Bridge and torch

people, a torch, at most two on the bridge. Sort times ascending. While more than 3 remain, move the two slowest using the cheaper of

  • the fastest escorts each: ;
  • the two fastest ferry: .

Finish with 3 people (), 2 () or 1 (). For the answer is 17 (the naive “fastest shuttles everyone” gives 19). Proof by exchange: the two slowest should cross together, and only the two fastest ever return. A bitmask DP over (who crossed, torch side) checks the greedy on small inputs.

Variants: a boat holding keeps the greedy shape but makes it harder to prove (DP is safer); different return costs, or some people unable to cross together, both need the full DP; minimising the number of crossings instead of total time is for ; multiple torches changes the structure entirely; a torch with a limited lifetime adds a feasibility check. This belongs to the same family as wolf/goat/cabbage, missionaries and cannibals, “jealous husbands” (a pairing constraint), and river crossing with a raft of capacity — all state-space searches, with bridge-and-torch unusual in also having a clean greedy. Whenever an obvious greedy feels forced, ask whether pairing the two worst items beats handling them separately — the same idea appears in Huffman coding. Full derivation and tested code: Bridge and Torch.

100 prisoners

Each of 100 prisoners may open 50 of 100 boxes. Strategy: start at your own number’s box and follow the permutation’s cycle. Everyone succeeds iff no cycle is longer than 50:

Lesson: correlating failures beats independent strategies, and the cycle structure of a random permutation is very predictable. A random permutation has cycles on average, and a given element lies in a cycle of length with probability exactly for every . Curtin and Warshauer (2006) proved cycle-following is not merely clever but provably optimal — no strategy does better.

The transferable idea is correlating failures: independent strategies multiply probabilities (, decaying exponentially), while cycle-following makes every prisoner’s fate depend on the same event, collapsing the product to one probability. The same trick recurs elsewhere:

SettingCorrelation trick
hat-guessing puzzlesagree on a parity convention ( of always correct, vs. expected independently)
distributed consensusshared randomness
derandomisationreplace independent bits with pairwise-independent ones
coupon collector variantscoordinate the sampling

Further permutation-cycle facts worth knowing on their own: expected number of fixed points is ; ; the expected length of the longest cycle is (the Golomb–Dickman constant); the expected length of the cycle containing a fixed element is ; and the number of permutations with exactly cycles is counted by the (unsigned) Stirling numbers of the first kind. The same “follow the permutation” idea is also a real algorithmic technique: in-place permutation application (apply with extra space by walking cycles), cycle sort (minimum swaps to sort number of cycles), permutation parity (), and computing per cycle by rotation — see also cycle detection in functional graphs.

Tested: the closed-form failure probability checked against a direct Monte Carlo simulation (generate random permutations, run the cycle-following strategy, measure the empirical failure rate) converging to the predicted for .

A random permutation also has cycles on average, and as (see derangements). Full derivation, optimality proof and tested code: 100 Prisoners.

Monty Hall

Switching wins with probability . The host’s knowledge is what matters: he always opens a goat door, so he gives no information about your door. Solve any variant with Bayes or by enumerating the joint distribution.

Host behaviour
always opens a goat door (standard)
opens a random door; it happened to be a goat
offers a switch only when you picked the car
offers a switch only when you picked a goat
opens a goat but prefers the lower-numbered door when free or , depending on which he opened

The puzzle is famous less for the answer than for how much it depends on this unstated host protocol — conditional probability depends on the process that generated the information, not just on the information itself. Related puzzles with the same lesson, each with its own dedicated note where one exists: the boy-or-girl paradox (“at least one boy” gives ; “the older is a boy” gives — identical stated fact, different conditioning), Bertrand’s box (three boxes of coins, answer not ), Sleeping Beauty (the reference class is genuinely ambiguous), the two envelopes problem (the naive switching argument is flawed), the base-rate fallacy (a rare disease with an accurate test still yields mostly false positives), and the prosecutor’s fallacy (). Full derivation and tested code: Monty Hall.

Secretary problem

candidates come in random order and you must accept or reject each on the spot. Reject the first , then take the first candidate better than all seen. That succeeds with probability . Variants: maximising the expected rank needs a threshold rule that changes with time (expected rank ); with choices allowed use multiple thresholds. These are the classic examples of online algorithms and optimal stopping, solved by backward DP over “candidates remaining”. The constant recurs throughout online decision-making (online bipartite matching, submodular-maximisation greedy, balls-into-bins), and the related prophet inequality (values drawn from known distributions) gives a -competitive threshold rule. Full derivation, the full variants table and the online-algorithms/competitive-ratio connection: Secretary Problem.

Poisoned wine and group testing

One of bottles is poisoned and tasters die after a fixed delay. With one round, tasters suffice: taster drinks the bottles with bit set, and the dead tasters spell the bottle’s index. With rounds a taster’s outcome is “dies in round or survives”, so tasters suffice (2 rounds and 3 tasters handle 27 bottles instead of 8). Lesson: the information-theoretic bound , and binary encoding as a construction. With poisoned bottles, outcomes must be distinguished and non-adaptive group-testing designs need tasters; if waiting between rounds is free, plain binary search solves with one taster and days. Full derivation and tested code: Poisoned Wine.

Counterfeit coin with a balance

Each weighing has 3 outcomes. With the heavier/lighter direction unknown, weighings handle coins (12 coins in 3 weighings); if a known-genuine reference coin is available, . With a known-heavier fake, coins. Lesson: ternary search and information bounds. Full derivation and tested code: Counterfeit Coin.

Celebrity problem

Find the person everyone knows who knows no one, using knows(a, b) queries. Keep a candidate . For each , if knows(c, i) then isn’t the celebrity, so set . Then verify with queries. At most queries in total, — and this is close to optimal, since queries are provably necessary in the worst case. Lesson: one comparison eliminates one candidate; with possible relationships, the answer is pinned down by examining only of them. Modelling “knows” as a directed graph, a celebrity is exactly a vertex with in-degree and out-degree : reading the full adjacency matrix finds it in by summing rows and columns, but the elimination algorithm never reads most of the matrix. At most one celebrity can exist (two would each have to know the other, contradicting “knows no one”). The same pattern finds a sink in a tournament.

Egg dropping, stairs, coins

These are the canonical DPs; see Classic DP. Egg dropping inverts nicely: = the most floors decidable with throws and eggs satisfies .

Grid and board puzzles

PuzzleTechnique
8/15-puzzlesolvability by permutation parity + blank row; IDA* with Manhattan + linear conflict (Informed Search)
Lights Outlinear system over ; or fix the first row ( choices) and chase the rest, or
N-queensbitmask backtracking; constructions exist for every
Knight’s tourWarnsdorff’s rule; closed tours exist on boards unless both odd, or , or with
Sudokuexact cover with dancing links, or bitmask backtracking choosing the most constrained cell
Peg solitaire / Conway’s soldierscolouring and weight invariants
Pancake sortingat most flips with the obvious greedy; the optimum is NP-hard
Domino and tromino tilingscolouring for impossibility; broken-profile DP to count; Kasteleyn’s formula for domino tilings of planar grids
Königsberg bridgesEuler path iff 0 or 2 odd vertices

Number puzzles

PuzzleAnswer
trailing zeros of in base 10; in base , (Legendre)
Chicken McNugget (coprime )largest non-representable ; exactly non-representable values
last non-zero digit of recurse on with a period-10 table, or compute by splitting into factors of 2 and 5
number of digits of , or Kamenetsky’s formula via Stirling
first digits of
derangements ( items, none in its own place), see inclusion–exclusion
staircase / ways to climb steps taking 1 or 2 at a timeFibonacci
counting brackets, triangulations, BSTs, mountain rangesall Catalan numbers , see Catalan
digit sums, repunits, palindromic numbers in a rangedigit DP, see Digit DP

Cross-reference: puzzle name technique

Puzzles that are really just a named instance of a technique covered in full elsewhere.

PuzzleTechnique
Maximum subarrayKadane, Classic Array Problems
Trapping rain watertwo pointers or monotonic stack, Monotonic Stack
Largest rectangle in a histogrammonotonic stack
Majority elementBoyer–Moore voting
Dutch national flagthree-way partition
Gas station / circular tourgreedy with a running deficit
Stock buy and sellgreedy, or DP by transaction count
Next greater elementmonotonic stack
Knapsack, coin change, rod cuttingDP, see Knapsack (coin change: greedy fails in general; rod cutting is unbounded knapsack)
Assignment problemHungarian algorithm, , see Assignment Problem
Stable marriageGale–Shapley, , see Stable Matching
Travelling salesmanNP-hard; Held–Karp for , see Hamiltonian Paths and TSP
Subset sum / partitionNP-hard in general; pseudo-polynomial DP when values are small