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] = &TrieNode{children: make(map[rune]*TrieNode)}
}
node = node.children[[1]]
}
node.isEnd = true
}The loop iterates over each character ch in the word. We use ch as the key to access or create the child node in the Trie.
Complete the code to check if a word exists in the Trie.
func (t *TrieNode) Search(word string) bool {
node := t
for _, ch := range word {
if node.children[[1]] == nil {
return false
}
node = node.children[ch]
}
return node.isEnd
}We check if the child node for the current character ch exists. If not, the word is not in the Trie.
Fix the error in the code to find if any word starts with the given prefix.
func (t *TrieNode) StartsWith(prefix string) bool {
node := t
for _, ch := range prefix {
if node.children[ch] == nil {
return false
}
node = node.children[[1]]
}
return true
}We must use the current character ch to move to the next child node while checking the prefix.
Fill both blanks to create a map comprehension that counts characters in a string.
counts := map[rune]int{}
for _, ch := range word {
counts[ch] [1] 1
}
result := map[rune]int{ch: counts[ch] [2] 0 for ch := range counts}We increment the count for each character using += 1. Then we create a new map with counts added to zero using + 0 to copy values.
Fill all three blanks to create a filtered map of characters with counts greater than zero.
filtered := map[rune]int{ch: counts[ch] for ch := range counts if counts[ch] [1] 0 && ch [2] 'a' && ch [3] '{' }We filter characters with counts greater than zero (>), and characters between 'a' and 'z' inclusive using >= and <.