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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>Solutions</strong> to Chapter 2 | Linked Lists<br />

2.1 Write code to remove duplicates from an unsorted linked list.<br />

FOLLOW UP<br />

How would you solve this problem if a temporary buffer is not allowed?<br />

pg 50<br />

SOLUTION<br />

If we can use a buffer, we can keep track of elements in a hashtable <strong>and</strong> remove any dups:<br />

1 public static void deleteDups(LinkedListNode n) {<br />

2 Hashtable table = new Hashtable();<br />

3 LinkedListNode previous = null;<br />

4 while (n != null) {<br />

5 if (table.containsKey(n.data)) previous.next = n.next;<br />

6 else {<br />

7 table.put(n.data, true);<br />

8 previous = n;<br />

9 }<br />

10 n = n.next;<br />

11 }<br />

12 }<br />

Without a buffer, we can iterate with two pointers: “current” does a normal iteration, while<br />

“runner” iterates through all prior nodes to check for dups. Runner will only see one dup<br />

per node, because if <strong>the</strong>re were multiple duplicates <strong>the</strong>y would have been removed already.<br />

1 public static void deleteDups2(LinkedListNode head) {<br />

2 if (head == null) return;<br />

3 LinkedListNode previous = head;<br />

4 LinkedListNode current = previous.next;<br />

5 while (current != null) {<br />

6 LinkedListNode runner = head;<br />

7 while (runner != current) { // Check for earlier dups<br />

8 if (runner.data == current.data) {<br />

9 LinkedListNode tmp = current.next; // remove current<br />

10 previous.next = tmp;<br />

11 current = tmp; // update current to next node<br />

12 break; // all o<strong>the</strong>r dups have already been removed<br />

13 }<br />

14 runner = runner.next;<br />

15 }<br />

16 if (runner == current) { // current not updated - update now<br />

17 previous = current;<br />

18 current = current.next;<br />

19 }<br />

20 }<br />

21 }<br />

1 0 5<br />

<strong>Cracking</strong> <strong>the</strong> <strong>Coding</strong> <strong>Interview</strong> | Data Structures

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

Saved successfully!

Ooh no, something went wrong!