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 20 | Hard<br />

20.13 Given a dictionary of millions of words, give an algorithm to find <strong>the</strong> largest possible<br />

rectangle of letters such that every row forms a word (reading left to right) <strong>and</strong> every<br />

column forms a word (reading top to bottom).<br />

SOLUTION<br />

pg 92<br />

Many problems involving a dictionary can be solved by doing some preprocessing. Where<br />

can we do preprocessing?<br />

Well, if we’re going to create a rectangle of words, we know that each row must be <strong>the</strong> same<br />

length <strong>and</strong> each column must have <strong>the</strong> same length. So, let’s group <strong>the</strong> words of <strong>the</strong> dictionary<br />

based on <strong>the</strong>ir sizes. Let’s call this grouping D, where D[i] provides a list of words of<br />

length i.<br />

Next, observe that we’re looking for <strong>the</strong> largest rectangle. What is <strong>the</strong> absolute largest rectangle<br />

that could be formed? It’s (length of largest word) * (length of largest word).<br />

1 int max_rectangle = longest_word * longest_word;<br />

2 for z = max_rectangle to 1 {<br />

3 for each pair of numbers (i, j) where i*j = z {<br />

4 /* attempt to make rectangle. return if successful. */<br />

5 }<br />

6 }<br />

By iterating in this order, we ensure that <strong>the</strong> first rectangle we find will be <strong>the</strong> largest.<br />

Now, for <strong>the</strong> hard part: make_rectangle. Our approach is to rearrange words in list1 into<br />

rows <strong>and</strong> check if <strong>the</strong> columns are valid words in list2. However, instead of creating, say,<br />

a particular 10x20 rectangle, we check if <strong>the</strong> columns created after inserting <strong>the</strong> first two<br />

words are even valid pre-fixes. A trie becomes h<strong>and</strong>y here.<br />

1 WordGroup[] groupList = WordGroup.createWordGroups(list);<br />

2 private int maxWordLength = groupList.length;<br />

3 private Trie trieList[] = new Trie[maxWordLength];<br />

4<br />

5 public Rectangle maxRectangle() {<br />

6 int maxSize = maxWordLength * maxWordLength;<br />

7 for (int z = maxSize; z > 0; z--) {<br />

8 for (int i = 1; i

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

Saved successfully!

Ooh no, something went wrong!