Given an array of strings words representing an English Dictionary, return the longest word inwordsthat can be built one character at a time by other words inwords.
If there is more than one possible answer, return the longest word with the smallest lexicographical order. If there is no answer, return the empty string.
Note that the word should be built from left to right with each additional character being added to the end of a previous word.
Input: words =["w","wo","wor","worl","world"]Output: "world"Explanation: The word "world" can be built one character at a time by "w","wo","wor", and "worl".
Input: words =["a","banana","app","appl","ap","apply","apple"]Output: "apple"Explanation: Both "apply" and "apple" can be built from other words in the dictionary. However,"apple"is lexicographically smaller than "apply".
To find the longest word that can be built one character at a time by other words, we need to ensure that all prefixes of the word exist in the dictionary. Using a Trie allows us to efficiently check for prefix existence, and BFS helps us find the longest word with the smallest lexicographical order.
classTrieNode {
val children = Array<TrieNode?>(26) { null }
var word = ""}
classSolution {
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.word = w
}
var ans = ""val q = ArrayDeque<TrieNode>()
q.add(root)
while (q.isNotEmpty()) {
val node = q.removeFirst()
if (node.word.length > ans.length || (node.word.length == ans.length && node.word < ans)) ans = node.word
for (i in0 until 26) {
node.children[i]?.let { if (it.word.isNotEmpty()) q.add(it) }
}
}
return ans
}
}
classTrieNode:
def__init__(self):
self.children = {}
self.word =""classSolution:
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.word = w
ans ="" q = [root]
while q:
node = q.pop(0)
if len(node.word) > len(ans) or (len(node.word) == len(ans) and node.word < ans):
ans = node.word
for child in node.children.values():
if child.word:
q.append(child)
return ans