Complete the code to initialize a new Trie node in Go.
func NewTrieNode() *TrieNode {
return &TrieNode{
children: make(map[rune]*TrieNode),
isEnd: [1],
}
}The isEnd field should be initialized to false when creating a new Trie node because initially it does not mark the end of a word.
Complete the code to insert a word into the Trie.
func (t *TrieNode) Insert(word string) {
node := t
for _, ch := range word {
if node.children[ch] == nil {
node.children[ch] = NewTrieNode()
}
node = node.children[[1]]
}
node.isEnd = true
}We use the current character 'ch' to move to the child node in the Trie.
Fix the error in the prefix search function to correctly check if a prefix exists in the Trie.
func (t *TrieNode) StartsWith(prefix string) bool {
node := t
for _, ch := range prefix {
if node.children[ch] == nil {
return [1]
}
node = node.children[ch]
}
return true
}If a character in the prefix is missing in the Trie, the prefix does not exist, so return false.
Fill both blanks to create a Hash Map based prefix search function.
func PrefixExists(words []string, prefix string) bool {
wordMap := make(map[string]bool)
for _, word := range words {
wordMap[word] = true
}
for w := range wordMap {
if len(w) >= len(prefix) && w[:[1]] == prefix {
return [2]
}
}
return false
}We compare the first len(prefix) characters of each word to the prefix. If matched, return true.
Fill all three blanks to implement a Trie prefix search that returns true if any word starts with the prefix.
func (t *TrieNode) SearchPrefix(prefix string) bool {
node := t
for _, ch := range prefix {
if node.children[[1]] == nil {
return [2]
}
node = node.children[ch]
}
return [3]
}Use 'ch' to check children. Return false if missing. Return true if prefix fully matched.