27.10.2014 Views

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>Solutions</strong> 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 <strong>and</strong> 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 />

pg 60<br />

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

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

on round 1, 3, 5, <strong>and</strong> 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 <strong>and</strong> 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 <strong>and</strong> square<br />

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

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

1 4 9<br />

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

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

Saved successfully!

Ooh no, something went wrong!