25.03.2013 Views

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

Solutions to Chapter 20 | Hard<br />

20 7 Write a program to find <strong>the</strong> longest word made of o<strong>the</strong>r words<br />

SOLUTION<br />

The solution below does <strong>the</strong> following:<br />

1 Sort <strong>the</strong> array by size, putting <strong>the</strong> longest word at <strong>the</strong> front<br />

2 For each word, split it in all possible ways That is, for “test”, split it into {“t”, “est”}, {“te”,<br />

“st”} and {“tes”, “t”}<br />

2 8 7<br />

<strong>Cracking</strong> <strong>the</strong> <strong>Coding</strong> <strong>Interview</strong> | Additional Review Problems<br />

pg 91<br />

3 Then, for each pairing, check if <strong>the</strong> first half and <strong>the</strong> second both exist elsewhere in <strong>the</strong><br />

array<br />

4 “Short circuit” by returning <strong>the</strong> first string we find that fits condition #3<br />

What is <strong>the</strong> time complexity of this?<br />

» Time to sort array: O(n log n)<br />

» Time to check if first / second half of word exists: O(d) per word, where d is <strong>the</strong> average<br />

length of a word<br />

» Total complexity: O(n log n + n * d) Note that d is fixed (probably around 5—10 characters)<br />

Thus, we can guess that for short arrays, <strong>the</strong> time is estimated by O(n * d) , which<br />

also equals O(number of characters in <strong>the</strong> array) For longer arrays, <strong>the</strong> time will be better<br />

estimated by O(n log n)<br />

» Space complexity: O(n)<br />

Optimizations: If we didn’t want to use additional space, we could cut out <strong>the</strong> hash table This<br />

would mean:<br />

» Sorting <strong>the</strong> array in alphabetical order<br />

» Ra<strong>the</strong>r than looking up <strong>the</strong> word in a hash table, we would use binary search in <strong>the</strong> array<br />

» We would no longer be able to short circuit<br />

1 class LengthComparator implements Comparator {<br />

2 @Override<br />

3 public int compare(String o1, String o2) {<br />

4 if (o1.length() < o2.length()) return 1;<br />

5 if (o1.length() > o2.length()) return -1;<br />

6 return 0;<br />

7 }<br />

8 }

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

Saved successfully!

Ooh no, something went wrong!