#208
Medium Algorithms Implement trie prefix tree
Hash Table String Design Trie
69.2% acceptance
Feb 27, 2026
12396
163
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.
boolean search(String word) Returns true if the string word is in the trie (i.e., was inserted before), and false otherwise.
boolean startsWith(String prefix) Returns true if there is a previously inserted string word that has the prefix prefix, and false otherwise.
Solution
Rust
Time O(2^n)
Space O(n)
struct TrieNode {
children: std::collections::HashMap<char, TrieNode>,
is_end: bool,
}
struct Trie {
root: TrieNode,
}
use std::collections::HashMap;
impl Trie {
fn new() -> Self {
Trie {
root: TrieNode {
children: HashMap::new(),
is_end: false,
},
}
}
fn insert(&mut self, word: String) {
let mut node = &mut self.root;
for ch in word.chars() {
node = node.children.entry(ch).or_insert(TrieNode {
children: HashMap::new(),
is_end: false,
});
}
node.is_end = true;
}
fn search(&self, word: String) -> bool {
let mut node = &self.root;
for ch in word.chars() {
if let Some(next) = node.children.get(&ch) {
node = next;
} else {
return false;
}
}
node.is_end
}
fn starts_with(&self, prefix: String) -> bool {
let mut node = &self.root;
for ch in prefix.chars() {
if let Some(next) = node.children.get(&ch) {
node = next;
} else {
return false;
}
}
true
}
}
/*
* Your Trie object will be instantiated and called as such:
* let obj = Trie::new();
* obj.insert(word);
* let ret_2: bool = obj.search(word);
* let ret_3: bool = obj.starts_with(prefix);
*/