#1804
Medium Algorithms Implement trie ii prefix tree
Hash Table String Design Trie
63.4% acceptance
Mar 31, 2026
356
19
A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.
Implement the Trie class:
Trie() Initializes the trie object.
void insert(String word) Inserts the string word into the trie.
int countWordsEqualTo(String word) Returns the number of instances of the string word in the trie.
int countWordsStartingWith(String prefix) Returns the number of strings in the trie that have the string prefix as a prefix.
void erase(String word) Erases the string word from the trie.
Solution
Rust
Time O(2^n)
Space O(n)
use std::collections::HashMap;
struct Trie {
children: HashMap<u8, Trie>,
word_count: i32,
prefix_count: i32,
}
/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
impl Trie {
fn new() -> Self {
Trie {
children: HashMap::new(),
word_count: 0,
prefix_count: 0,
}
}
fn insert(&mut self, word: String) {
let mut node = self;
for b in word.bytes() {
node = node.children.entry(b).or_insert_with(Trie::new);
node.prefix_count += 1;
}
node.word_count += 1;
}
fn count_words_equal_to(&self, word: String) -> i32 {
let mut node = self;
for b in word.bytes() {
match node.children.get(&b) {
Some(child) => node = child,
None => return 0,
}
}
node.word_count
}
fn count_words_starting_with(&self, prefix: String) -> i32 {
let mut node = self;
for b in prefix.bytes() {
match node.children.get(&b) {
Some(child) => node = child,
None => return 0,
}
}
node.prefix_count
}
fn erase(&mut self, word: String) {
let mut node = self;
for b in word.bytes() {
node = node.children.get_mut(&b).unwrap();
node.prefix_count -= 1;
}
node.word_count -= 1;
}
}
/*
* Your Trie object will be instantiated and called as such:
* let obj = Trie::new();
* obj.insert(word);
* let ret_2: i32 = obj.count_words_equal_to(word);
* let ret_3: i32 = obj.count_words_starting_with(prefix);
* obj.erase(word);
*/