Math paradoxes

The 100 prisoners problem Each one has 50%. What about all together?Together they have 31%.

Each of 100 prisoners gets only 50 tries to find their number among 100 boxes. All go free only if every one of them succeeds. What are the odds with the best strategy? Lock in your answer, then check it with a game, a simulation and four explanations.

Each of 100 prisoners gets only 50 tries to find their number among 100 boxes. If they search at random, all of them succeed with probability 7.9·10⁻³¹, which is practically never. But there is a simple strategy that wins almost a third of the time. Check it with a game, a simulation and four explanations.

Make a guess
7.9·10⁻³¹chance with random search
31.2%chance with the loop strategy

The puzzle

A hundred prisoners, a hundred boxes, one chance

The computer scientists Anna Gál and Peter Bro Miltersen first studied the problem in 2003. It looks hopeless: each prisoner finds their number with probability 1/2, whatever they do. Yet together they can win almost a third of the time.

  1. 1

    Prisoners and boxes

    A prison holds 100 prisoners numbered 1 to 100. A room holds 100 boxes with the same numbers on their lids.

  2. 2

    Numbers inside

    The warden puts one slip with a prisoner's number in each box. The slips are shuffled at random, and each number is in exactly one box.

  3. 3

    The search

    The prisoners enter the room one at a time. Each may open 50 boxes to look for their own number. Then they leave, and the room is put back as it was.

  4. 4

    The win condition

    If every one of the 100 prisoners finds their number, all go free. If even one fails, all stay in prison. They may agree on a plan in advance, but cannot communicate once it starts.

Intuition says

"Each one succeeds with chance 1/2, so together it's (1/2)¹⁰⁰. That's zero"

For random search that's true. But the prisoners can agree on a strategy that links their results: either they all succeed together, or many fail at once. Then the overall chance is 31.2%.

Is there a plan?

Searching at random means each prisoner guesses independently of the others. Can they agree on a plan that beats random search? Think it over before you guess.

The slips are placed at random, and the warden doesn't know the prisoners' plan.

The loop strategy

  • Open the box with your own number.
  • Read the number on the slip inside.
  • Open the box with that number, and repeat.

Why "loop". Say you are prisoner #7. Box 7 holds 12, box 12 holds 3, box 3 holds 7. You found your number on the third try, and the next step of the chain 7 → 12 → 3 would lead back to box 7, where you started: it closes into a loop. It always works this way: the box just before the return holds your number. So you are sure to find your number if your loop is at most 50 boxes long.

Why it helps. All the prisoners whose boxes sit on the same loop walk that same loop. They win or lose together. So everyone goes free if the arrangement has no loop longer than 50. Your own chance is still 1/2, but the prisoners' failures are no longer independent. More in round 4.

The slips are placed at random, and the warden doesn't know the plan. What happens if he does is in round 5.

Round 1 · Guess

What are the prisoners' best odds?

Suppose the prisoners pick the best possible strategy. What is the probability that all 100 go free? Lock in your answer before reading on.

Hints

Hard to decide? Open the hints one at a time: the easy one first, then stronger ones.

Next: the solution

Next comes the explanation, with spoilers

The next rounds reveal the strategy that saves the prisoners: a game, a simulation and the explanation. Answer round 1 first, or go on?

You chose to always show all rounds.

Round 2 · Play a prisoner

20 boxes, 10 tries

Let's shrink the prison: 20 prisoners, 20 boxes, each opens 10. You are one of the prisoners. Try the loop strategy:

  1. open the box with your own number;
  2. read the number inside;
  3. open the box with that number, and so on.

Why "loop". When you find your number, it points to the first box you opened: the chain has closed into a loop. Hence the name.

Compare it with a random search, or open any boxes you like. Then run all 20 prisoners and see whether they go free.

Your number7
Tries left10
Your games–

All 20 prisoners

A dot is a box with its number. An arrow leads from a box to the box whose number lies inside. One arrow leaves each box and one enters it, so the 20 boxes always split into a few closed loops. A prisoner who follows the loop walks the loop their box is on. Loops longer than 10 are pink: there, the tries run out.

    Round 3 · Simulation

    10,000 random arrangements

    The computer shuffles 100 numbers into boxes thousands of times and finds the longest loop in each arrangement. The prisoners win when it is at most 50 long. The bars are the simulation; the line is the exact formula.

    Length of the longest loop

    ≤ 50: everyone goes free ≥ 51: the prisoners lose exact formula
    Simulation · all go free
    –
    Exact formula
    –

    What about 1,000 or a million prisoners?

    exact formula simulation, 2,000 arrangements per dot limit 1 − ln 2

    Each prisoner opens half of the boxes. More prisoners means slightly lower odds, but they never fall below 1 − ln 2 ≈ 30.69%. Even a million prisoners win almost a third of the time.

    Once you answer, the simulation code appears here so you can run it yourself.

    Check it yourself in code

    The same simulation, short and with no libraries. Run the JavaScript in your browser console (F12) or in Node; the Python needs only the standard library.

    JavaScript
    // 100 prisoners, the loop strategy: each opens their own box, then the box with the number found inside, up to 50 times.
    const N = 100, TRIES = 50, TRIALS = 100000;
    
    function allFree() {
      const box = [...Array(N).keys()];               // box[i] is the number in box i
      for (let i = N - 1; i > 0; i--) {               // shuffle at random
        const j = Math.floor(Math.random() * (i + 1));
        [box[i], box[j]] = [box[j], box[i]];
      }
      for (let p = 0; p < N; p++) {                   // prisoner p
        let b = p, found = false;
        for (let t = 0; t < TRIES && !found; t++) {
          found = box[b] === p;
          b = box[b];                                 // next: the box with the number inside
        }
        if (!found) return false;
      }
      return true;
    }
    
    let wins = 0;
    for (let i = 0; i < TRIALS; i++) if (allFree()) wins++;
    let exact = 1;                                    // 1 − (1/51 + … + 1/100)
    for (let k = TRIES + 1; k <= N; k++) exact -= 1 / k;
    console.log(`all go free: simulation ${(100 * wins / TRIALS).toFixed(2)}%, exact ${(100 * exact).toFixed(2)}%`);
    
    Python
    # 100 prisoners, the loop strategy: each opens their own box, then the box with the number found inside, up to 50 times.
    import random
    
    N, TRIES, TRIALS = 100, 50, 100_000
    
    
    def all_free():
        box = list(range(N))                  # box[i] is the number in box i
        random.shuffle(box)
        for p in range(N):                    # prisoner p
            b = p
            for _ in range(TRIES):
                if box[b] == p:
                    break
                b = box[b]                    # next: the box with the number inside
            else:
                return False                  # 50 tries and no own number
        return True
    
    
    wins = sum(all_free() for _ in range(TRIALS))
    exact = 1 - sum(1 / k for k in range(TRIES + 1, N + 1))
    print(f"all go free: simulation {100 * wins / TRIALS:.2f}%, exact {100 * exact:.2f}%")
    
    Round 4 · Four explanations

    Why the loop works

    The strategy doesn't change any single prisoner's chance: it stays 1/2. It changes how those chances are linked to each other.

    In plain wordspictures, analogies, small numbers

    “In plain words” is hidden on all puzzles.

    An arrangement is made of loops

    An arrow from each box to the number inside

    Think of Secret Santa. Everyone gives one gift and gets one. Start with yourself and keep asking "who do you give to?": from you to the person you give to, from them to the person they give to, and so on. Sooner or later you reach the person who gives to you, and from them you are back at yourself. The circle has closed.

    Boxes work the same way. A slip only tells you a number, and a number names a box. So the one thing you can do with a slip is go to the box with that number. Draw an arrow from each box to the box named by the slip inside.

    Exactly one arrow leaves each box, because it holds one slip. Exactly one enters each box, because each number is in exactly one box. So when you follow the arrows, you never hit a dead end: every box holds a number, so there is always a next box. And you can't run into the middle of your own path: each box has only one incoming arrow, and you have already used it. There are only so many boxes, so the walk must come back to a box it has seen, and the only one it can come back to is the box where you started. That is why the arrows always close up into loops. Mathematicians call them the cycles of the .

    Your loop

    You find your number if your loop is at most 50 long

    You start at the box with your number and follow the arrows. Your number is in exactly one box; call it X. X's arrow points to the box with your number, the one where you started. Could you circle forever without returning to your box? Only if some box had two arrows coming in, and none does. So the walk comes back to your box, and the last box you open before that is X, the one with your number. You always find your number when the loop closes. The only question is whether 50 tries are enough.

    So the prisoners win if the arrangement has no loop longer than 50. There can be at most one long loop: two loops of 51 don't fit into 100 boxes.

    Results are linked

    All win together, or many lose together

    Random: each one independent7.9·10⁻³¹chance all 100 succeed
    Loop: fates linked31.2%chance all 100 succeed

    With either strategy, 50 prisoners fail on . But with the loop strategy the failures bunch up in the same arrangements: everyone on a long loop fails together. When the prisoners lose, about 73 of them fail on average. In exchange, in 31% of arrangements nobody fails.

    Then why does each prisoner's own chance stay exactly 1/2? The loop through your box is equally likely to have any length from 1 to 100. Exactly half of those lengths are 50 or less, so you find your number with probability 1/2, just as at random. The plan doesn't raise anyone's own chance. It piles the failures onto the same arrangements. Compare a bad plan, "everyone opens boxes 1–50": it fails exactly 50 prisoners every time, those whose numbers are in boxes 51–100.

    Every case at a glance

    4 prisoners, 2 tries each: all 24 arrangements

    Four numbers fit into four boxes in 24 ways. Each card below is one arrangement: the numbers in boxes 1, 2, 3, 4 and the loops it is made of. With the loop strategy the prisoners win when no loop is longer than 2.

    Random: each one independent1/16(1/2)⁴, that is 6.25%
    Loop: winning arrangements10/24that is 41.7%

    Each prisoner alone finds their number half the time, with the loop and at random alike. The difference is how those successes are spread: with the loop, all four win in 10 arrangements, and in the other 14 several prisoners fail at once, the ones on the long loop.

    Rigoroustables, charts, formulas

    “Rigorous” is hidden on all puzzles.

    Counting long loops

    The chance of a loop of length k is 1/k

    For k from 51 to 100, the chance that the arrangement has a loop of length exactly k is 1/k. These events don't overlap, since there's only one long loop. So the chance of losing is 1/51 + 1/52 + … + 1/100 ≈ 68.8%.

    For formula lovers

    The exact answer and its limit

    How many arrangements have a loop of length k longer than half. Count in three steps:

    • choose the k boxes of the loop: C(n, k) ways;
    • join them in a circle: (k − 1)! ways;
    • arrange the other n − k boxes any way you like: (n − k)! ways.
    Permutations with a loop of lengthk>n/2 =C(n,k)·(k−1)!·(n−k)!=n!k

    The chance of losing: a long loop of length k from 51 to 100 occurs with chance 1/k. Hn = 1 + 1/2 + … + 1/n is a .

    P(lose)=151+152+…+1100 =H100−H50≈0.6882

    The chance that everyone goes free: there is no long loop.

    P(all free)=1−(H100−H50)≈0.3118

    What happens with very many prisoners: the difference of harmonic numbers tends to ln 2.

    n→∞:Hn−Hn/2→ln2 ⇒P→1−ln2≈0.3069

    For comparison: if every prisoner opens boxes at random.

    P(random)=(12)100≈7.9·10−31

    Here Hn = 1 + 1/2 + … + 1/n is a harmonic number. To build a loop of length k, choose k boxes, join them in a circle in (k − 1)! ways, and arrange the rest any way you like. This strategy is the best possible: no other plan gives better odds.

    Round 5 · Harder versions

    Other numbers of tries and a malicious warden

    What if the prisoners may open more or fewer boxes? And what should they do if the warden knows their plan and places the numbers on purpose? At the end, a few other agreements that lose to the loop.

    n prisoners, each opens k boxes

    With the loop strategy
    At random

    Chance by number of tries

    loop strategy at random

    The malicious warden

    The warden has learned about the loop strategy. He places the numbers so that all 100 boxes form one big loop. Then no prisoner finds their number in 50 tries.

    All free, 10,000 runs
    Longest loop the prisoners see

    Be the warden yourself

    10 boxes, each prisoner opens 5. Right now the prisoners win. Tap one box, then another: their slips swap places. Break the loop strategy in as few swaps as you can.

    The loops of your 10 boxes

    Swapping the slips of two boxes on different loops merges those loops into one. A swap inside one loop cuts it in two.

    What if they get 60 tries?

    100 prisoners. Press "Check": 10,000 simulated arrangements show the exact formula is right.

    Tries eachAll free (exact)

    What about other agreements?

    Each plan below also has to be agreed in advance, and each loses to the loop. 100 prisoners, 50 tries. "Check" runs every plan on 10,000 arrangements.

    PlanEach finds theirsAll free

    In almost every plan each prisoner alone finds their number half the time. The plans differ in whether the prisoners fail together. Boxes 1–50 make sure half of them always fail. Two halves tie the prisoners' fates a little, which is already 12.6 times better than random, yet still hopeless. The loop from your own box gathers all the failures on one long loop. Start from someone else's box and you walk someone else's loop: even your own chance drops.

    Real data · Try it on yourself

    Shuffle a real deck

    You don't have to trust a computer shuffle. Check it with your own hands: 10 cards become 10 boxes, and you'll see whether your prisoners would go free.

    1. Take the ace, two, three and so on up to the ten of one suit. The ace means 1.
    2. Shuffle these 10 cards well and lay them in a row face down. They are boxes 1–10, left to right.
    3. Turn the cards over and type their values in order, separated by spaces.

    The loops of your deck

    The card in position 1 tells you which position to open next, and so on round the loop. Each of the 10 prisoners opens 5 cards. Loops longer than 5 are coloured: the prisoners on them lose.

    Bonus · Fun facts

    Things to tell your friends

    2003

    A puzzle from a research paper

    Anna Gál and Peter Bro Miltersen described the problem in a paper on data structures at the ICALP 2003 conference. Their version used coloured strips of paper, not prisoners. Their Aarhus University colleague Sven Skyum pointed them to the loop strategy.

    2006

    It can't be beaten

    Eugene Curtin and Max Warshauer proved that the loop strategy is optimal: no other plan gives the prisoners better odds. The proof appeared in The Mathematical Intelligencer in a paper called "The locker puzzle".

    YouTube

    The puzzle that went viral

    The Veritasium channel brought the puzzle to a wide audience. The video's title calls it a riddle that seems impossible even once you know the answer.

    9.33·10¹⁵⁷

    That's how many arrangements exist

    100 numbers can be placed in 100 boxes in 100! ways. That number has 158 digits. In about 31% of them the longest loop is at most 50.

    ≈ 73

    They lose as a crowd

    When the loop strategy fails, about 73 prisoners fail on average: everyone on the long loop. With random search about 50 fail on average, and almost never none at all.

    30.69%

    A million prisoners is fine

    However many prisoners there are, if each opens half of the boxes, the chance that all go free never drops below 1 − ln 2 ≈ 30.69%. For 100 prisoners it's 31.18%; for 1,000 it's 30.74%.

    Surprises in Probability

    Henk Tijms

    2019 · chapter 8

    Algebraic Combinatorics

    Richard P. Stanley

    2013 · pp. 187–189

    All books →
    Discussion

    What do you think?

    Share your own explanation, an objection or a variant of the puzzle. You need a GitHub account to comment.

    Is “Advanced” the right level for this puzzle?

    Thank you! This helps set the levels right.

    Newsletter

    New puzzles, explanations and discussions

    I keep adding new puzzles, new ways to explain them and write-ups of the discussions they start. Leave your email and I'll write when something new is out. No spam, one-click unsubscribe.

    The sign-up form will appear here soon.