The Longest Word With All Prefixes coding problem asks you to analyze an array of strings and find the longest string such that every single prefix of that string is also present in the array. If there is a tie for the longest string, return the one that appears earliest lexicographically. It is essentially identical to "Longest Word in Dictionary" but explicitly phrased around prefix validation.
This problem is a direct assessment of a candidate's ability to build and navigate a Trie (Prefix Tree). While Hash Set solutions work, companies like Google ask this specific variant to force candidates into implementing tree-based data structures. It tests your understanding of node traversal, flag setting (isEndOfWord), and recursive string building.
The absolute best pattern for this is the Trie.
isWord = true).isWord flag is true! This ensures that every prefix leading up to the current character is a valid word in the array. Track the longest path found during this DFS.Array: ["a", "b", "c", "ab", "bc", "abc"]
Construct the Trie. Nodes marked * are valid words:
a* -> b* -> c*b* -> c*c*Traverse via DFS:
a*. Valid. Path: "a".a*, go down to b*. Valid. Path: "ab".b*, go down to c*. Valid. Path: "abc". Max length is 3.b* -> c*? Path "bc" length 2.
The longest word built strictly through valid nodes is "abc".
If "ab" was missing from the array, the b node under a would not be marked isWord, so the DFS would stop at "a", failing to reach "abc".When using the Trie DFS approach, candidates often struggle with the lexicographical tie-breaker. A brilliant trick to avoid messy string comparisons after the DFS is to iterate through the Trie children from 'z' down to 'a' (or vice-versa depending on how you update your max variable). If you evaluate 'a' before 'z', and strictly use > (greater than) for length updates, the lexicographically smaller string naturally wins ties.
When preparing for the Longest Word With All Prefixes interview question, commit the basic Trie node class to memory. It should contain a map or array of children (Node[26]) and a boolean isWord. Being able to code a Trie insertion method fluidly in under two minutes gives you massive confidence and leaves you plenty of time to focus on the DFS logic.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Remove Sub-Folders from the Filesystem | Medium | Solve | |
| Words Within Two Edits of Dictionary | Medium | Solve | |
| Concatenated Words | Hard | Solve | |
| Longest Common Suffix Queries | Hard | Solve | |
| Replace Words | Medium | Solve |