25.03.2013 Views

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

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.

Solutions to Chapter 19 | Moderate<br />

19 8 Design a method to find <strong>the</strong> frequency of occurrences of any given word in a book<br />

SOLUTION<br />

CareerCup com<br />

pg 89<br />

The first question – which you should ask your interviewer – is if you’re just asking for a<br />

single word (“single query”) or if you might, eventually, use <strong>the</strong> same method for many different<br />

words (“repetitive queries”)? That is, are you simply asking for <strong>the</strong> frequency of “dog”,<br />

or might you ask for “dog,” and <strong>the</strong>n “cat,” “mouse,” etc?<br />

Solution: Single Query<br />

In this case, we simply go through <strong>the</strong> book, word by word, and count <strong>the</strong> number of times<br />

that a word appears This will take O(n) time We know we can’t do better than that, as we<br />

must look at every word in <strong>the</strong> book<br />

Solution: Repetitive Queries<br />

In this case, we create a hash table which maps from a word to a frequency Our code is <strong>the</strong>n<br />

like this:<br />

1 Hashtable setupDictionary(String[] book) {<br />

2 Hashtable table =<br />

3 new Hashtable();<br />

4 for (String word : book) {<br />

5 word = word.toLowerCase();<br />

6 if (word.trim() != “”) {<br />

7 if (!table.containsKey(word)) table.put(word, 0);<br />

8 table.put(word, table.get(word) + 1);<br />

9 }<br />

10 }<br />

11 return table;<br />

12 }<br />

13<br />

14 int getFrequency(Hashtable table, String word) {<br />

15 if (table == null || word == null) return -1;<br />

16 word = word.toLowerCase();<br />

17 if (table.containsKey(word)) {<br />

18 return table.get(word);<br />

19 }<br />

20 return 0;<br />

21 }<br />

Note: a problem like this is relatively easy. Thus, <strong>the</strong> interviewer is going to be<br />

looking heavily at how careful you are. Did you check for error conditions?<br />

2 7 4

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

Saved successfully!

Ooh no, something went wrong!