Longest Word with All Prefixes
Longest Word with All Prefixes is a GFG problem (Medium). Given an array of lowercase strings words, find the longest string such that every one of its prefixes is also in words.
- A prefix here means the first 1, 2, 3, … letters, up to the whole word. So
"abc"needs"a","ab"and"abc"in the list. - If several valid strings share the longest length, return the alphabetically smallest.
- If no string is valid, return
"".
The practice page titles it Longest Valid Word with All Prefixes, and the function to write is longestValidWord(words).
- 1 <= words.size <= 1000
- 1 <= words[i].size <= 100
- Words consist of lowercase English letters
Intuition
In a trie, the prefixes of a word are exactly the nodes on its path from the root. Insert every word and mark the node where each one ends. Then a word is valid when every node on its path carries an end mark, because each marked node is a prefix that appears in the list as a whole word.
- Build: one insert per word; words with a shared start share nodes.
- Check: walk each word from the root and stop at the first unmarked node.
- Pick: keep the longest valid word, and on equal length the alphabetically smaller one.
"Every prefix must also be present" points to a trie: one walk down a word visits all of its prefixes in order, so the check costs one step per letter.
Approach
Before reading on, think about where a word's prefixes live in a trie and what extra bit each node needs. Then decide how to break ties without sorting. Aim for time linear in the total number of letters.
Build the trie
For each word, walk down from the root, creating a child for each missing letter, and set end = True on the node of the last letter. A node is marked only when some word in the list ends exactly there.
Check every prefix of a word
Walk the word again from the root. At each letter, move to the child and require end on it. An unmarked node means that prefix is not in the list, so stop and reject the word.
Keep the best word
When a word passes, replace best if the word is longer, or the same length and smaller in dictionary order. Starting from best = "" means the empty answer comes out on its own when nothing passes.
Code in Python, C++ and Java
Common pitfalls
Checking that the path exists instead of the end marks
node = node.children.get(ch)
if node is None:
ok = Falsenode = node.children[ch]
if not node.end:
ok = FalseEvery word's own path exists once it is inserted, so this test passes everything. On ["a", "apple"] it returns "apple", though "ap", "app" and "appl" are missing; the right answer is "a".
Letting a later word win a tie
if ok and len(w) >= len(best):
if ok and (len(w) > len(best) or
(len(w) == len(best) and w < best)):With >=, the last valid word of the top length wins, whatever its spelling. On ["a", "b"] it returns "b" instead of "a".
Edge cases
["cat", "cats"]Both walks stop at the first node, because "c" is not in the list. best never changes and the function returns "".
Complexity
Longest Word with All Prefixes FAQ
Can you solve it without a trie?
Yes. Put every word in a hash set, then for each word test w[:1], w[:2], … against the set. Building each prefix string costs up to its length, so one word of length L costs O(L²) instead of O(L). With words of up to 100 letters that still runs fast; the trie just avoids rebuilding the same prefixes.
LeetCode 1858 has the same name. Is it the same problem?
Yes, it is the same task (a premium problem there), with larger limits: up to 10⁵ letters in total. The trie solution above handles those limits unchanged, since it is linear in the total letter count.
How is this different from Longest Word in Dictionary?
Longest Word in Dictionary (LeetCode 720) asks for the longest word that can be built one letter at a time from other words in the list. That is the same condition as every prefix being present, with the same tie-break, so this trie code solves it too once the method is renamed to longestWord.