package main import "fmt" // TrieNode represents a node in the Trie type TrieNode struct { children map[rune]*TrieNode isWord bool } // Trie structure type Trie struct { root *TrieNode } // Insert inserts a word into the Trie func (t *Trie) Insert(word string) { node := t.root for _, ch := range word { if node.children[ch] == nil { node.children[ch] = &TrieNode{children: make(map[rune]*TrieNode)} } node = node.children[ch] } node.isWord = true } // LongestWord finds the longest word with all prefixes present func (t *Trie) LongestWord() string { var result string var dfs func(node *TrieNode, path []rune) dfs = func(node *TrieNode, path []rune) { if len(path) > len(result) || (len(path) == len(result) && string(path) < result) { result = string(path) } for ch := range node.children { child := node.children[ch] if child.isWord { dfs(child, append(path, ch)) } } } dfs(t.root, []rune{}) return result } func main() { words := []string{"a", "app", "ap", "apply", "apple", "appl"} trie := &Trie{root: &TrieNode{children: make(map[rune]*TrieNode)}} for _, w := range words { trie.Insert(w) } fmt.Println(trie.LongestWord()) }
The code builds a Trie and searches for the longest word where every prefix is also a word in the list. Among the words, "apple" and "apply" are longest. Both "apple" and "apply" have all prefixes present, but lex order chooses "apple".
The 'isWord' boolean marks if the path to this node forms a complete word in the dictionary. This is crucial to check if all prefixes exist when searching for the longest word.
func (t *Trie) LongestWord() string {
var result string
var dfs func(node *TrieNode, path []rune)
dfs = func(node *TrieNode, path []rune) {
if len(path) > len(result) || (len(path) == len(result) && string(path) < result) {
result = string(path)
}
for ch := range node.children {
child := node.children[ch]
// Missing check: if child.isWord
dfs(child, append(path, ch))
}
}
dfs(t.root, []rune{})
return result
}Without checking if child.isWord, the DFS explores nodes that do not represent complete words, so the result may include words whose prefixes are not valid words, violating the problem's condition.
"world" has all prefixes "w", "wo", "wor", "worl" present as words. "word" also has prefixes but is shorter. "war" is shorter and "worl" is prefix but not longest.
When multiple words have the same length, the problem requires choosing the lexicographically smallest one. Comparing strings lex order ensures this.