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 10 | Ma<strong>the</strong>matical<br />

Q3 -> append x*3, x*5 and x*7 to Q3, Q5 and Q7. Remove x from Q3.<br />

Q5 -> append x*5 and x*7 to Q5 and Q7. Remove x from Q5.<br />

Q7 -> only append x*7 to Q7. Remove x from Q7.<br />

Note: we do not need to append x*3 and x*5 to all lists because<br />

<strong>the</strong>y will already be found in ano<strong>the</strong>r list.<br />

6. Repeat steps 4 - 6 until we’ve found k elements.<br />

1 public static int getKthMagicNumber(int k) {<br />

2 if (k 0; --k) { // We’ve done one iteration already.<br />

11 val = Math.min(Q3.peek().intValue(),<br />

12 Math.min(Q5.peek().inValue(), Q7.peek().intValue()));<br />

13 if (val == Q7.peek()) {<br />

14 Q7.remove();<br />

15 } else {<br />

16 if (val == Q5.peek()) {<br />

17 Q5.remove();<br />

18 } else { // must be from Q3<br />

19 Q3.remove();<br />

20 Q3.add(val * 3);<br />

21 }<br />

22 Q5.add(val * 5);<br />

23 }<br />

24 Q7.add(val * 7);<br />

25 }<br />

26 return val;<br />

27 }<br />

OBSERVATIONS AND SUGGESTIONS:<br />

When you get this question, do your best to solve it—even though it’s really difficult Explain<br />

a brute force approach (not as tricky) and <strong>the</strong>n start thinking about how you can optimize it<br />

Or, try to find a pattern in <strong>the</strong> numbers<br />

Chances are, your interviewer will help you along when you get stuck Whatever you do,<br />

don’t give up! Think out loud, wonder aloud, explain your thought process Your interviewer<br />

will probably jump in to guide you<br />

CareerCup com<br />

1 9 6

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

Saved successfully!

Ooh no, something went wrong!