1. Hash Set Prefix Verification for All Words
Intuition
Insert words into unordered_set<string>. For each word, check set.count(word.substr(0, k)) for k from 1 to word.length(). If all exist, compare with current best (longer length, or smaller lexicographical).
When to apply: Quick brute force baseline.
Algorithm
- Step 1: Insert all words into an unordered set.
- Step 2: Initialize
best = "". - Step 3: For each word in words: check if all prefixes exist in the set.
- Step 4: If valid, update
bestifword.length() > best.length()or(word.length() == best.length() && word < best). - Step 5: Return
best.
#include <iostream>#include <string>#include <vector>#include <unordered_set>using namespace std; class Solution {public: string longestWord(vector<string>& words) { unordered_set<string> dict(words.begin(), words.end()); string best = ""; for (const string& w : words) { bool valid = true; for (size_t k = 1; k < w.length(); k++) { if (!dict.count(w.substr(0, k))) { valid = false; break; } } if (valid) { if (w.length() > best.length() || (w.length() == best.length() && w < best)) { best = w; } } } return best; }}; int main() { Solution sol; vector<string> words = {"w","wo","wor","worl","world"}; cout << "Longest word: " << sol.longestWord(words) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N * L^2)— Generates L substrings per word, taking O(L2) time for N words. - Space complexity:
O(N * L)— Stores all words in the hash set.
Why Brute Force Doesn't Scale:
With 1,000 words of length 30, brute force checks 30,000 prefixes via hash table lookups.
Trie DFS navigates only the valid subgraph in a single pass of O(Total characters * 26).