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.4 You have an array with all <strong>the</strong> numbers from 1 to N, where N is at most 32,000. The<br />

array may have duplicate entries <strong>and</strong> you do not know what N is. With only 4KB of<br />

memory available, how would you print all duplicate elements in <strong>the</strong> array?<br />

SOLUTION<br />

pg 72<br />

We have 4KB of memory which means we can address up to 8 * 4 * (2^10) bits. Note that 32*<br />

(2^10) bits is greater than 32000. We can create a bit vector with 32000 bits, where each bit<br />

represents one integer.<br />

NOTE: While this isn’t an especially difficult problem, it’s important to implement this cleanly.<br />

We will define our own bit vector class to hold a large bit vector.<br />

1 public static void checkDuplicates(int[] array) {<br />

2 BitSet bs = new BitSet(32000);<br />

3 for (int i = 0; i < array.length; i++) {<br />

4 int num = array[i];<br />

5 int num0 = num - 1; // bitset starts at 0, numbers start at 1<br />

6 if (bs.get(num0)) {<br />

7 System.out.println(num);<br />

8 } else {<br />

9 bs.set(num0);<br />

10 }<br />

11 }<br />

12 }<br />

13<br />

14 class BitSet {<br />

15 int[] bitset;<br />

16<br />

17 public BitSet(int size) {<br />

18 bitset = new int[size >> 5]; // divide by 32<br />

19 }<br />

20<br />

21 boolean get(int pos) {<br />

22 int wordNumber = (pos >> 5); // divide by 32<br />

23 int bitNumber = (pos & 0x1F); // mod 32<br />

24 return (bitset[wordNumber] & (1 > 5); // divide by 32<br />

29 int bitNumber = (pos & 0x1F); // mod 32<br />

30 bitset[wordNumber] |= 1

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

Saved successfully!

Ooh no, something went wrong!