DSA Trie

Longest Word With All Prefixes

Find the longest dictionary word whose every prefix is also in the dictionary — DFS on a trie of words.

Medium
Time O(W * L) Space O(W * L)
5 min read
trie dfs

Problem#

Given a list of words, return the longest word such that every prefix of it (of length 1, 2, …, length of word) is also present in the list. If multiple have the same length, return the lexicographically smallest. If none qualify, return "". This is an curriculum variant of LeetCode 720 “Longest Word in Dictionary”.

Examples#

  • words = ["k","ki","kir","kira","kiran"]"kiran".
  • words = ["k","kira"]"" (no "ki" or "kir").
  • words = ["w","wo","wor","worl","world","b","br","bre","brea","break"]"break".

Constraints#

  • 1 <= words.length <= 5 * 10^4, lowercase letters.

Hints#

Hint
DFS the trie only along child nodes whose isEnd is true — that guarantees every prefix exists.

Approach#

Insert every word into a trie. DFS from the root descending only into isEnd children. Track the deepest valid path; on ties prefer lexicographically smaller (DFS in a..z order naturally gives this).

Solution#

Longest Word With All Prefixes
class Solution {
struct Node {
Node* child[26]{};
bool isEnd = false;
};
public:
string longestWord(vector<string>& words) {
Node* root = new Node();
for (auto& w : words) {
Node* cur = root;
for (char c : w) {
int i = c - 'a';
if (!cur->child[i]) cur->child[i] = new Node();
cur = cur->child[i];
}
cur->isEnd = true;
}
string best, path;
function<void(Node*)> dfs = [&](Node* node) {
if ((int)path.size() > (int)best.size()) best = path;
for (int i = 0; i < 26; ++i) {
if (node->child[i] && node->child[i]->isEnd) {
path.push_back('a' + i);
dfs(node->child[i]);
path.pop_back();
}
}
};
dfs(root);
return best;
}
};

Editorial#

The trie guarantees: descending into an isEnd child means the cumulative path corresponds to an inserted word, which means every prefix on the way is itself an inserted word. Iterating children in a..z order and updating best only when strictly longer breaks ties lexicographically without an explicit comparison.

Complexity#

  • Time: O(sum of word lengths) for build, O(W * L) for DFS.
  • Space: O(sum of word lengths) for the trie.

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.