Menu

Earn Premium with Referrals

Invite your friends and earn Premium rewards through our referral program.

See how it works and start inviting friends.

Prisoners & Hats
INTERVIEWPUZZLE

Prisoners & Hats

Solve a classic prisoners-and-hats puzzle using shared information, logical deduction, and reasoning about what others can see.

The Puzzle: 100 prisoners are standing in a line, all facing the same direction.

  • Each prisoner wears a Black or White hat.
  • A prisoner can see the hats of everyone in front of them, but not their own or those behind them.
  • Starting from the back (who sees 99 hats), each prisoner must guess their hat color.
  • If they guess correctly, they live. If wrong, they die.
  • They can hear the guesses of the prisoners behind them. How many can they save with a pre-planned strategy?

1. The Strategy: Parity

They can save 99 prisoners for sure, and the 100th (the first to guess) has a 50% chance of living.

The Code:

  • The first prisoner (at the back) counts the number of Black hats he see in front of him.
  • If the count is EVEN, he says “Black”.
  • If the count is ODD, he says “White”.
  • (He may die, but he has just provided the “Parity Bit” for everyone else!)

The Deduction (Prisoner 99):

  • Prisoner 99 knows the total parity (from Prisoner 100’s shout).
  • He looks at the 98 hats in front of him.
  • If the parity of what he sees matches the total parity, his own hat must be White. If it changed, his hat must be Black.
  • The next prisoner does the same, but also considers the guesses already made behind him.

2. Example

  • 3 Prisoners: (Back) B, W, B (Front)
  • Prisoner 1 (Back) sees W and B. Count of Black = 1 (ODD). He says “White”.
  • Prisoner 2 sees B. He knows the total Black count was ODD. Since he sees 1 Black, his own must be White (otherwise the total would be even). He says “White” (Lives!).
  • Prisoner 3 knows the total was ODD. P2 said White. Total Black still ODD. He hears P2’s guess. He says “Black” (Lives!).

Interview-Focused Questions

A: This is exactly how a Checksum or a Parity Bit works. One bit of information is used to “protect” or describe the state of the remaining bits. If the state changes (an error or a specific hat color), it can be detected by the receiver.

Q: What if there were 3 hat colors (Red, Green, Blue)?

A: Then the first prisoner would use Modular Arithmetic (Base 3). He would sum the colors (Assign R=0, G=1, B=2) and shout the color corresponding to Sum % 3.

Q: Does the first prisoner always die?

A: No, he has a 50% chance of his parity guess coincidentally matching his own hat color. But the strategy ensures everyone else lives regardless of his fate.

Key Takeaway

This puzzle tests your ability to use cumulative state to derive individual values.

My Private Notes

Notes are auto-saved locally to this device.