Here is a suggested strategy:
The last prisoner responds “Red” if the number of red hats in front of him is even, or “Blue” if it is odd.
Let’s solve an example to demonstrate how this strategy works. Consider the line of prisoners indicated in Figure 1.
We will use sequences formed by the letters R (Red) and B (Blue) to represent a line of prisoners. Thus, in the example in Figure 1, we have the sequence: B R B B R B.
Therefore, the last prisoner sees: R B B R B. He counts the number of red hats he sees: 2. Since it is an even number, he answers “Red.”
The fifth prisoner sees: B B R B. He counts the number of red hats he sees: 1. He knows that the last prisoner saw an even number of red hats, so he deduces that his hat is red. He answers “Red.”
The fourth prisoner sees: B R B. He counts the number of red hats he sees: 1. He knows that the last prisoner saw an even number of red hats and that the hat of the fifth prisoner is red, so he deduces that his hat is blue.
The next prisoners use the same reasoning.
Thus, everyone (except the last prisoner) has the necessary information to correctly answer the color of their hat.