Longest Word in Dictionary (LeetCode 720): Solution and Explanation
Find the longest word whose every prefix is also in the list, breaking ties by the lexicographically smallest word.
Intuition
A word like "apple" is buildable only if "a", "ap", "app" and "appl" are all words too. Checking each prefix separately for every word repeats a lot of work.
A trie stores all the prefixes once. Each word becomes a path from the root, and we mark the node where each word ends.
In that trie, a word is buildable exactly when every node on its path is marked. So a DFS that only steps into marked children visits exactly the buildable words, and it can never wander into a branch that is broken higher up.
Approach: Trie plus DFS through word ends
- Insert every word into a trie and store the word on the node where it ends.
- Run a DFS from the root that tries the letters a to z in order.
- Step into a child only if it ends a word; skip the whole branch otherwise.
- Each node reached is a buildable word. Replace best only when it is strictly longer, so the alphabetically first word of each length wins.
- Return best, which stays empty if no single-letter word exists.
Step-by-step example
words = ["w","wo","wor","worl","world"]
- Insert the five words. They share one path w-o-r-l-d, and every node on it is marked as a word end.
- The DFS starts at the root and finds child 'w', which is a word. best becomes "w".
- From 'w' it steps into 'o' ("wo" is a word), then 'r', then 'l', each one longer than best.
- Finally it reaches 'd' and best becomes "world". There are no more children.
- Return "world".
Code: Python, Java, C++
1class Solution:
2 def longestWord(self, words: List[str]) -> str:
3 root = {}
4 for w in words:
5 node = root
6 for ch in w:
7 node = node.setdefault(ch, {})
8 node['#'] = w
9 best = ''
10
11 def dfs(node):
12 nonlocal best
13 for ch in sorted(k for k in node if k != '#'):
14 child = node[ch]
15 if '#' in child:
16 if len(child['#']) > len(best):
17 best = child['#']
18 dfs(child)
19
20 dfs(root)
21 return best1class Solution {
2 private static class Node {
3 Node[] next = new Node[26];
4 String word;
5 }
6 private String best = "";
7
8 public String longestWord(String[] words) {
9 Node root = new Node();
10 for (String w : words) {
11 Node node = root;
12 for (char ch : w.toCharArray()) {
13 int c = ch - 'a';
14 if (node.next[c] == null) node.next[c] = new Node();
15 node = node.next[c];
16 }
17 node.word = w;
18 }
19 best = "";
20 dfs(root);
21 return best;
22 }
23
24 private void dfs(Node node) {
25 for (int c = 0; c < 26; c++) {
26 Node child = node.next[c];
27 if (child != null && child.word != null) {
28 if (child.word.length() > best.length()) best = child.word;
29 dfs(child);
30 }
31 }
32 }
33}1class Solution {
2 struct Node {
3 Node* next[26] = {};
4 string word;
5 bool end = false;
6 };
7 string best;
8
9 void dfs(Node* node) {
10 for (int c = 0; c < 26; c++) {
11 Node* child = node->next[c];
12 if (child && child->end) {
13 if (child->word.size() > best.size()) best = child->word;
14 dfs(child);
15 }
16 }
17 }
18
19public:
20 string longestWord(vector<string>& words) {
21 Node* root = new Node();
22 for (const string& w : words) {
23 Node* node = root;
24 for (char ch : w) {
25 int c = ch - 'a';
26 if (!node->next[c]) node->next[c] = new Node();
27 node = node->next[c];
28 }
29 node->end = true;
30 node->word = w;
31 }
32 best = "";
33 dfs(root);
34 return best;
35 }
36};Time and space complexity
O(L)
L is the total number of letters across all words. Each letter is inserted once and each trie node is visited at most once by the DFS (26 child slots per node is a constant).
O(L)
The trie has at most one node per letter, plus the recursion depth of up to 30.
Other approaches
Sort and grow a set (time O(L log n), space O(L))
Sort the words, then keep a set of buildable words starting from the empty string. A word is buildable if the word without its last letter is in the set. Sorting puts prefixes first and makes the first longest word the smallest one.
Check every prefix with a hash set (time O(sum of len^2), space O(L))
Put all words in a set and, for each word, test all of its prefixes. Simple, but it costs O(len^2) per word for slicing.
Common mistakes
- Only checking that the word minus its last letter exists. "apple" needs "a", "ap", "app" and "appl", not just "appl".
- Replacing best on equal length. With alphabetical DFS order the first word of a length is already the smallest, so ties must keep it.
- Forgetting the empty answer. If no word has length 1, nothing can be built and the result is "".
- Iterating a hash map of children in arbitrary order, which breaks the tie rule. Children must be tried a to z.
Frequently asked questions
Why does the DFS only step into nodes that end a word?
Because a word is buildable only when all of its prefixes are words. If a node is not a word end, every word below it is missing that prefix, so the whole branch can be skipped.
How are ties broken without comparing strings?
The DFS tries letters in alphabetical order, so it reaches words of the same length in lexicographic order. Updating best only on a strictly longer word keeps the first, smallest one.
What if the list has duplicate words?
Duplicates follow the same trie path and mark the same node again, so they change nothing.
Is the trie faster than sorting?
The trie is linear in the number of letters, while sorting adds a log factor. At these limits both are fast; the trie mainly makes the prefix chain easy to see.