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 11 | System Design <strong>and</strong> 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 />

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