25.03.2013 Views

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Solutions to Chapter 6 | Brain Teasers<br />

6 6 There are one hundred closed lockers in a hallway A man begins by opening all one<br />

hundred lockers Next, he closes every second locker Then he goes to every third<br />

locker and closes it if it is open or opens it if it is closed (e g , he toggles every third<br />

locker) After his one hundredth pass in <strong>the</strong> hallway, in which he toggles only locker<br />

number one hundred, how many lockers are open?<br />

SOLUTION<br />

Question: For which rounds is a door toggled (open or closed)?<br />

1 4 9<br />

<strong>Cracking</strong> <strong>the</strong> <strong>Coding</strong> <strong>Interview</strong> | Concepts and Algorithms<br />

pg 60<br />

A door n is toggled once for each factor of n, including itself and 1 That is, door 15 is toggled<br />

on round 1, 3, 5, and 15<br />

Question: When would a door be left open?<br />

Answer: A door is left open if <strong>the</strong> number of factors (x) is odd You can think about this by<br />

pairing factors off as an open and a close If <strong>the</strong>re’s one remaining, <strong>the</strong> door will be open<br />

Question: When would x be odd?<br />

Answer: x is odd if n is a perfect square Here’s why: pair n’s factors by <strong>the</strong>ir complements<br />

For example, if n is 36, <strong>the</strong> factors are (1, 36), (2, 18), (3, 12), (4, 9), (6, 6) Note that (6, 6) only<br />

contributes 1 factor, thus giving n an odd number of factors<br />

Question: How many perfect squares are <strong>the</strong>re?<br />

Answer: There are 10 perfect squares You could count <strong>the</strong>m (1, 4, 9, 16, 25, 36, 49, 64, 81,<br />

100), or you could simply realize that you can take <strong>the</strong> numbers 1 through 10 and square<br />

<strong>the</strong>m (1*1, 2*2, 3*3, , 10*10)<br />

Therefore, <strong>the</strong>re are 10 lockers open

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!