12.2. Brainteaser Problems
Brainteasers draw from a much broader and more diverse body of knowledge than programming and technical problems, so a comprehensive review isn't possible here. The following brainteasers will hone your problem-solving skills in preparation for an interview.
12.2.1. Count Open Lockers
Suppose you are in a hallway lined with 100 closed lockers. You begin by opening all 100 lockers. Next, you close every second locker. Then you go to every third locker and close it if it is open or open it if it is closed (call this toggling the locker). You continue toggling every n th locker on pass number n. After your hundredth pass of the hallway, in which you toggle only locker number 100, how many lockers are open?
In a hall with k lockers, how many lockers remain open after pass k?
This problem is designed to seem overwhelming. You don't have time to draw a diagram of 100 lockers and count 100 passes through them. Even if you did, solving the problem that way wouldn't illustrate any skill or intuition, so there must be some trick that can be used to determine how many doors will be open. You just have to figure out what that trick is.
It's unlikely that you're going to be able to intuit the solution to this problem by just staring at it. What can you do? Although it's not practical to solve the entire problem by brute force, solving a few lockers in this manner is reasonable. Perhaps you'll notice some patterns you can apply to the larger problem.