Four prisoners named P1, P2, P3 and P4 are arrested for a crime, but the jail is full and the jailer has nowhere to put them. He eventually comes up with the solution of giving them a puzzle and if they answer correctly they can go free but if they fail they are to be executed.

The jailer makes prisoners P1, P2 and P3 stand in a single file. Prisoner P4 is put behind a screen. The arrangement looks like this:

P1 P2 P3 || P4

The ‘||’ is the screen.

The jailer tells them that there are two black hats and two white hats; that each prisoner is wearing one of the hats; and that each of the prisoners is only able to see the hats in front of them but not on themselves or behind. Prisoner P1 can see P2 and P3. Prisoner P2 can see P3 only. The fourth man, P4, behind the screen can’t see or be seen by any other prisoner. No communication between the prisoners is allowed.

If any prisoner can figure out and tell the jailer the color of the hat he has on his head all four prisoners go free. If any prisoner gives an incorrect answer, all four prisoners are executed. How the prisoners can escape, regardless of how the jailer distributes the hats?

You can assume that the prisoners can all hear each other if one of them tries to answer the question. Also, every prisoner thinks logically and knows that the other prisoners think logically as well.

The prisoners know that there are only two hats of each color. So if P1 observes that P2 and P3 have hats of the same color, P1 would deduce that his own hat is the opposite color. However, if P2 and P3 have hats of different colors, then P1 will not be able to guess correctly.

The key is that prisoner P2, after allowing an appropriate interval, and knowing what P1 would do, can deduce that if P1 does not say anything then the hats on P2 and P3 must be different. Being able to see P3’s hat he can deduce his own hat color.