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 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 />

pg 91<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”} <strong>and</strong> {“tes”, “t”}.<br />

3. Then, for each pairing, check if <strong>the</strong> first half <strong>and</strong> <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 />

»»<br />

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

»»<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 />

»»<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 />

»»<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 />

»»<br />

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

»»<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 />

»»<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 }<br />

2 8 7<br />

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

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

Saved successfully!

Ooh no, something went wrong!