Cracking the Code Interview




Comment hidden because of low score. Click to expand.
1
of 1 vote

The solution is correct.

Okay, let's say C = 1. What will happen in this case? The person with the hat will see that no one else has a hat and remove it that night.

So, if C = 1, the hats are all gone after the first night. Do you agree with that? Are you sure? Okay. Great.

Suppose C = 2. Both hat-wearing people look around and see one other person with a hat. They know that C = 1 or C = 2, but they don't know which of these it is. But they *do* know that, if C = 1, then that other person would have removed their hat the first night [from the above paragraph]. So, after the first night, if both people see that the other person is still wearing a hat, then they must conclude that C != 1. Therefore, C = 2 and they have the other hat. That night, they both remove their hats.

So, if C = 2, the hats are all gone after the second night. Note that *both* hats are removed simultaneously.

Suppose C = 3. Again, the hat-wearers know that either C = 2 or C = 3. They also know that, if C = 2, then the hats will be removed on the second night. When the hats are not removed, they conclude that C = 3. They all remove their hats on the third night.

... and so on.

- Gayle L McDowell June 03, 2013 | Flag Reply




Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More