25.03.2013 Views

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

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.

Solutions to Chapter 11 | System Design and Memory Limits<br />

11 3 Given an input file with four billion integers, provide an algorithm to generate an<br />

integer which is not contained in <strong>the</strong> file Assume you have 1 GB of memory<br />

FOLLOW UP<br />

What if you have only 10 MB of memory?<br />

SOLUTION<br />

CareerCup com<br />

pg 72<br />

There are a total of 2^32, or 4 billion, distinct integers possible We have 1 GB of memory, or<br />

8 billion bits<br />

Thus, with 8 billion bits, we can map all possible integers to a distinct bit with <strong>the</strong> available<br />

memory The logic is as follows:<br />

1 Create a bit vector (BV) of size 4 billion<br />

2 Initialize BV with all 0’s<br />

3 Scan all numbers (num) from <strong>the</strong> file and write BV[num] = 1;<br />

4 Now scan again BV from 0th index<br />

5 Return <strong>the</strong> first index which has 0 value<br />

1 byte[] bitfield = new byte [0xFFFFFFF/8];<br />

2 void findOpenNumber2() throws FileNotFoundException {<br />

3 Scanner in = new Scanner(new FileReader(“input_file_q11_4.txt”));<br />

4 while (in.hasNextInt()) {<br />

5 int n = in.nextInt ();<br />

6 /* Finds <strong>the</strong> corresponding number in <strong>the</strong> bitfield by using <strong>the</strong><br />

7 * OR operator to set <strong>the</strong> nth bit of a byte (e.g.. 10 would<br />

8 * correspond to <strong>the</strong> 2nd bit of index 2 in <strong>the</strong> byte array). */<br />

9 bitfield [n / 8] |= 1

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

Saved successfully!

Ooh no, something went wrong!