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

Create successful ePaper yourself

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

<strong>Solutions</strong> to Chapter 6 | Brain Teasers<br />

6.3 You have a five quart jug <strong>and</strong> a three quart jug, <strong>and</strong> an unlimited supply of water<br />

(but no measuring cups). How would you come up with exactly four quarts of water?<br />

NOTE: The jugs are oddly shaped, such that filling up exactly ‘half’ of <strong>the</strong> jug would<br />

be impossible.<br />

SOLUTION<br />

We can pour water back <strong>and</strong> forth between <strong>the</strong> two jugs as follows:<br />

5 Quart Contents 3 Quart Contents Note<br />

5 0 Filled 5 quart jug<br />

2 3 Filled 3Q with 5Q’s contents<br />

0 2 Dumped 3Q<br />

5 2 Filled 5Q<br />

4 3 Fill remainder of 3Q with 5Q<br />

4 Done! We have four quarts.<br />

OBSERVATIONS AND SUGGESTIONS:<br />

pg 60<br />

» » Many brain teasers have a math / CS root to <strong>the</strong>m—this is one of <strong>the</strong>m! Note that as<br />

long as <strong>the</strong> two jug sizes are relatively prime (i.e., have no common prime factors), you<br />

can find a pour sequence for any value between 1 <strong>and</strong> <strong>the</strong> sum of <strong>the</strong> jug sizes.<br />

1 4 5<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!