Longest Word in Dictionary
Find the longest word in a list that can be built one letter at a time from other words in the same list.
Given a list of lowercase words, return the longest word that can be built one letter at a time, where every prefix, a start of the word, is also a word in the list. For "apple""a""ap""app""appl"""
Example 1
Output: "world"
Example 2
Output: "apple"
Explanation: "apple" and "apply" can both be built, and "apple" comes first in alphabetical order. But "banana" cannot be built, because "b" is not in the list.
The Idea
Picture a word game where you lay down one letter tile at a time, and after every tile the letters on the table must spell a word from the list. In Example 2, "apple""apply""banana"
Checking a word means checking every start of it, and many words start the same way. The words "apple""apply"
Store the words so that shared starts are stored once. Begin with an empty box, the root. Each letter of a word is a link to a new box, and two words that begin with the same letters follow the same links for as long as their letters agree. Look at the picture below, built from Example 2.
From the root, the link a leads to the box a, then the link p to the box ap, and so on to appl. There the path splits: the link e leads to apple and the link y to apply. Each box is labelled with the letters spelled on the way to it. The box where a word's last letter lands is marked as the end of a word. In the picture, those boxes have a solid border, as the legend "a word ends here" shows. A tree of letter links like this, where words with the same start share a path, is called a trie.
Now look at the dashed boxes along the bottom, labelled "only a prefix". The link b leads to the box b, but no word in the list is just "b", so that box is not a word end. The prefixes ba, ban, bana and banan are not in the list either. Only the last box, banana, ends a word.
So a word can be built one letter at a time exactly when every box on its path from the root ends a word. Follow the orange line marked "the path to apple": a, ap, app, appl and apple all end words. The question for each word turns into a walk: start at the root, step only into boxes that end a word, and keep the longest word you reach. The walk stops at the box b, "not a word: stop", so "banana"
One question is left: apply has the same length as apple and is "reached later", as the picture notes. If the walk tries the links of each box in alphabetical order, it goes down e before y, so it meets apple first. Keeping the first word of each length then gives the alphabetically smallest one.
Solution Approach
Turning that walk into code means settling three things: how to store the trie, how to walk only through boxes that end a word, and how to settle ties between words of the same length.
Storing the trie
Why build a trie at all, instead of putting the words in a HashSet"apple""apple""apply"
In the trie, each box is a small Nodenextnext[0]next[1]nullwordnull
Walking only through word ends
In what order should the walk visit the boxes? From the root it goes a, ap, app, appl, apple, as deep as it can along one path. Then it backs up to appl to try the link y, and later all the way back to the root to try the link b. Going deep along one path before backing up to try the next link is called a depth-first search, or DFS for short.
A method dfs(node)nodewordnull
Settling ties
Which word wins when two have the same length? The loop in dfsnext
Java Solution
The method longestWord
- First, create an empty
node. For each wordroot , a markerw starts atcur and moves down one letter at a time. The slot index isroot , and wheni = ch - 'a' is empty, a new node is created there. After the last letter,cur.next[i] marks the end of the word.cur.word = w - Next, call the helper
, which walks the trie. Its loop takes the children of a node in order fromdfs(root) tonext[0] and enters a child only when it is notnext[25] and itsnull is notword .null - For each child it enters,
compares the child's word withdfs , the longest word found so far, which starts asbest . A strictly longer word replaces"" . Thenbest calls itself on the child, to go one letter deeper.dfs - When the walk has come back to the root,
returnslongestWord .best
The main["b", "ab"]"kit""mit"solvebest
public class LongestWordInDictionary {
private static class Node {
Node[] next = new Node[26]; // one slot per letter, 'a' to 'z'
String word; // the word that ends here, or null
}
private String best = "";
public String longestWord(String[] words) {
Node root = new Node();
for (String w : words) {
Node cur = root;
for (char ch : w.toCharArray()) {
int i = ch - 'a';
if (cur.next[i] == null) {
cur.next[i] = new Node();
}
cur = cur.next[i];
}
cur.word = w; // mark the end of w
}
dfs(root);
return best;
}
// Walk only into nodes where a word ends, so every prefix on the way is a word.
private void dfs(Node node) {
for (Node child : node.next) { // children in order 'a' to 'z'
if (child != null && child.word != null) {
if (child.word.length() > best.length()) {
best = child.word; // strictly longer only
}
dfs(child);
}
}
}
static String solve(String... words) {
return "\"" + new LongestWordInDictionary().longestWord(words) + "\"";
}
public static void main(String[] args) {
System.out.println(solve("w", "wo", "wor", "worl", "world"));
System.out.println(solve("a", "banana", "app", "appl", "ap", "apply", "apple"));
System.out.println(solve("b", "ab"));
System.out.println(solve("ab", "abc"));
System.out.println(solve("k", "ki", "kit", "m", "mi", "mit"));
}
}
Running it prints:
"world"
"apple"
"b"
""
"kit"
On the second line, "apple""apply""banana""b""ab""a"
In ["ab", "abc"]"kit""mit""kit"
The test child.word.length() > best.length()>=main"apply""mit"
Complexity
The work is one pass over the letters to build the trie, plus one walk over its boxes. Let T be the total number of letters in all the words together.
- Time: O(T), because building the trie handles each of the T letters once, and the walk enters each box at most once and scans its 26 slots, a fixed amount per box.
- Space: O(T) boxes of 26 slots each, because each letter can create its own box, and the chain of
calls is only as deep as the longest word.dfs
How a trie inserts and finds words, step by step, is covered in