Longest Word With All Prefixes Problem
Description
LeetCode Problem 1858.
Given an array of strings words, find the longest string in words such that every prefix of it is also in words.
- For example, let
words = ["a", "app", "ap"]. The string"app"has prefixes"ap"and"a", all of which are inwords.
Return the string described above. If there is more than one string with the same length, return the lexicographically smallest one, and if no string exists, return "".
Example 1:
Input: words = ["k","ki","kir","kira", "kiran"]
Output: "kiran"
Explanation: "kiran" has prefixes "kira", "kir", "ki", and "k", and all of them appear in words.
Example 2:
Input: words = ["a", "banana", "app", "appl", "ap", "apply", "apple"]
Output: "apple"
Explanation: Both "apple" and "apply" have all their prefixes in words.
However, "apple" is lexicographically smaller, so we return that.
Example 3:
Input: words = ["abc", "bc", "ab", "qwe"]
Output: ""
Constraints:
1 <= words.length <= 10^51 <= words[i].length <= 10^51 <= sum(words[i].length) <= 10^5words[i]consists only of lowercase English letters.
Solution
Approach: Trie
Put every word into a trie. A node has 26 child slots and a flag that marks the end of a word.
A word qualifies when every prefix of it is itself a word. Walk the word down the trie: each node we step onto must be flagged as the end of a word. If one is not, some prefix is missing and the word is rejected.
Go through words once more and keep the best qualifying word: the longest one, and among equal lengths the lexicographically smallest.
Complexity: O(L) time and O(L) space, where L is the total length of all words.
class Trie:
__slots__ = ["children", "is_end"]
def __init__(self):
self.children: Optional[List[Trie]] = [None] * 26
self.is_end: bool = False
def insert(self, w: str) -> None:
node = self
for c in w:
idx = ord(c) - ord("a")
if not node.children[idx]:
node.children[idx] = Trie()
node = node.children[idx]
node.is_end = True
def search(self, w: str) -> bool:
node = self
for c in w:
idx = ord(c) - ord("a")
node = node.children[idx]
if not node.is_end:
return False
return True
class Solution:
def longestWord(self, words: List[str]) -> str:
trie = Trie()
for w in words:
trie.insert(w)
ans = ""
for w in words:
if (len(w) > len(ans) or len(w) == len(ans) and w < ans) and trie.search(w):
ans = w
return ans