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 in words.
Return _the string described above. If there is more than one string with the same length, return thelexicographically smallest one, and if no string exists, return _"".
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:
1
2
3
4
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:
1
2
Input: words =["abc","bc","ab","qwe"]Output: ""
Constraints:
1 <= words.length <= 10^5
1 <= words[i].length <= 10^5
1 <= sum(words[i].length) <= 10^5
words[i] consists only of lowercase English letters.
To find the longest word where every prefix is also in the list, we use a Trie to store all words and then perform DFS, only continuing down paths where all prefixes are valid words. This ensures that the word we build has all its prefixes present.
classTrieNode {
val children = Array<TrieNode?>(26) { null }
var isWord = false}
classSolution {
var ans = ""fundfs(node: TrieNode, path: StringBuilder) {
if (path.length > ans.length || (path.length == ans.length && path.toString() < ans)) ans = path.toString()
for (i in0 until 26) {
node.children[i]?.let {
if (it.isWord) {
path.append('a'+i)
dfs(it, path)
path.deleteCharAt(path.length-1)
}
}
}
}
funlongestWord(words: Array<String>): String {
val root = TrieNode()
for (w in words) {
var node = root
for (c in w) {
val idx = c - 'a'if (node.children[idx] ==null) node.children[idx] = TrieNode()
node = node.children[idx]!! }
node.isWord = true }
dfs(root, StringBuilder())
return ans
}
}
classTrieNode:
def__init__(self):
self.children = {}
self.is_word =FalseclassSolution:
deflongestWord(self, words: list[str]) -> str:
root = TrieNode()
for w in words:
node = root
for c in w:
if c notin node.children:
node.children[c] = TrieNode()
node = node.children[c]
node.is_word =True ans =""defdfs(node, path):
nonlocal ans
if len(path) > len(ans) or (len(path) == len(ans) and path < ans):
ans = path
for c in sorted(node.children):
child = node.children[c]
if child.is_word:
dfs(child, path + c)
dfs(root, "")
return ans