The Wayback Machine - https://web.archive.org/web/20250804224443/https://www.geeksforgeeks.org/aptitude/puzzle-13-100-prisoners-with-redblack-hats/
Open In App

Puzzle | 100 Prisoners with Red/Black Hats

Last Updated : 30 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

100 prisoners stand in a line, each wearing a red or black hat. They can see the hats of those in front, but not their own or those behind. Starting from the last prisoner (who sees all others), each is asked to guess their own hat colour. A correct guess means survival; an incorrect one means execution. Before this starts, prisoners may discuss a strategy, but no communication is allowed during the process.

100 Prisoners with Red/Black Hats


Check if you were right - full answer with solution below. 

Solution: 

At most, 99 prisoners can be guaranteed to be saved using a pre-agreed strategy based on parity (even or odd count) of red hats. The 100th prisoner (last in line) has a 50-50 chance of survival, but his answer conveys critical information to save the rest.

  • The 100th prisoner counts the number of red hats in front of him.
  • If it's even, he says “Red”; if odd, he says “Black”. His answer encodes the parity of red hats for the others to use.

Logic for 99th Prisoner:

If the 100th said "Red" ( even red hats in front):

  • If the 99th sees even red hats : his hat is black.
  • If the 99th sees odd red hats : his hat is red.

If the 100th said "Black" ( odd red hats in front):

  • If the 99th sees even red hats : his hat is red.
  • If the 99th sees odd red hats : his hat is black.

The 98th prisoner applies the same logic, now using the updated parity based on what has been said before. In this way, prisoners from 99th to 1st can guarantee survival.

Or

They can also use a strategy where two prisoners start at the front of the line.

  • If their hat colors match, the third prisoner stands behind them.
  • If their hat colors are different, the third stands between them.
  • This continues, with each new prisoner joining at the point where a color change is detected, or going to the end if no change occurs; gradually sorting the group by hat color.

In the end, prisoners are arranged with same-colored hats grouped together (e.g., 50 red, 50 black). The last prisoner says the color of the hat of the person in front of him, and the 51st prisoner adjusts his answer accordingly. This pattern helps others determine their own hat colors.
 


Article Tags :

Similar Reads