Hats In Jail

According to the story, four prisoners 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 so if they succeed they can go free but if they fail they are executed.

The jailer puts three of the men sitting in a line. The fourth man is put behind a screen (or in a separate room). He gives all four men party hats (as in diagram). The jailer explains that there are two red and two blue hats; that each prisoner is wearing one of the hats; and that each of the prisoners is only to see the hats in front of them but not on themselves or behind. The fourth man 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 say to the jailer what color hat he has on his head all four prisoners go free. If any prisoner suggests an incorrect answer, all four prisoners are executed. The puzzle is to find how the prisoners can escape, regardless of how the jailer distributes the hats?

Answer:

If the third prisoner sees that both prisoners in front are wearing same-colored hats, then he knows he must be wearing a different-colored hat.

If he does not, and does not guess correctly, then the remaining two prisoners must be wearing a red and a blue hat. The second prisoner can see the hat in front of him and knows that his own hat must be the opposite color. So if he sees a red hat he answers blue and vice versa.