Longest Word With All Prefixes - Problem
Find the longest word that can be built one character at a time!
Given an array of strings
For example, with
• The word
• Both prefixes exist in the original array
• So
Special Rules:
• If multiple words have the same longest length, return the lexicographically smallest one
• If no valid word exists, return an empty string
• A word is considered its own prefix
Given an array of strings
words, you need to find the longest string where every prefix of it also exists in the array. Think of it as building a word letter by letter, where each intermediate step must also be a valid word in your collection.For example, with
words = ["a", "app", "ap"]:• The word
"app" has prefixes "a" and "ap"• Both prefixes exist in the original array
• So
"app" is valid!Special Rules:
• If multiple words have the same longest length, return the lexicographically smallest one
• If no valid word exists, return an empty string
• A word is considered its own prefix
Input & Output
example_1.py — Basic Case
$
Input:
["w","wo","wor","worl","world"]
›
Output:
"world"
💡 Note:
The word "world" has all its prefixes ("w", "wo", "wor", "worl") present in the array, making it the longest valid word.
example_2.py — Lexicographic Tie
$
Input:
["a", "banana", "app", "appl", "ap", "apply", "apple"]
›
Output:
"apple"
💡 Note:
Both "apple" and "apply" have length 5 and all prefixes present. "apple" comes first lexicographically.
example_3.py — No Valid Word
$
Input:
["abc", "bc", "ab", "qwe"]
›
Output:
""
💡 Note:
No word has all its prefixes in the array. For example, "abc" needs "a" and "ab", but "a" is missing.
Visualization
Tap to expand
Understanding the Visualization
1
Start Simple
Begin with single-letter words that exist in your array
2
Build Gradually
Add one letter at a time, ensuring each step creates a valid word
3
Track Progress
Keep building as long as intermediate results remain valid words
4
Find Longest
The longest word you can build following this rule is your answer
Key Takeaway
🎯 Key Insight: Use a Trie to naturally validate prefix chains - each path from root represents a buildable word sequence where every intermediate step is guaranteed to be a complete word.
Time & Space Complexity
Time Complexity
O(n × m + result_length)
O(n × m) to build the Trie, plus O(result_length) for DFS traversal to find the longest path
✓ Linear Growth
Space Complexity
O(n × m × 26)
Trie can store up to n×m×26 nodes in worst case (each character can have 26 children)
⚡ Linearithmic Space
Constraints
- 1 ≤ words.length ≤ 1000
- 1 ≤ words[i].length ≤ 30
- words[i] consists of only lowercase English letters
- All strings in words are unique
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code