Trie Autocomplete Implementation in Rust
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Trie Autocomplete runs in O(m) time and O(n*m) space, in Rust as in every other language.
- ✓No trie in std. The node is a plain struct that owns its children: std::collections::BTreeMap<char, Node> when you want sorted suggestions for free, std::collections::HashMap<char, Node> when order does not matter.
- ✓Children own their nodes directly (BTreeMap<char, Node>); a reviewer will ask why you wrote Box<Node> per edge when the map already heap-allocates.
- ✓The Rust trap: The derived Drop glue is recursive: dropping the root drops each child, which drops each grandchild, one stack frame per trie level.
- ✓std HashMap defaults to SipHash-1-3, a DoS-resistant hash that is dramatically oversized for a 4-byte char key; swapping in FxHashMap or ahash typically halves the descent cost, and a fixed [Option<Box<Node>>; 26] array removes hashing entirely for ASCII alphabets.
What Trie Autocomplete actually is
Trie Autocomplete in Rust: what you actually reach for
Rust implementation
use std::collections::BTreeMap;
#[derive(Default)]
pub struct Node {
children: BTreeMap<char, Node>,
is_word: bool,
}
impl Node {
pub fn insert(&mut self, word: &str) {
let mut cur = self;
for ch in word.chars() {
cur = cur.children.entry(ch).or_default();
}
cur.is_word = true;
}
pub fn complete(&self, prefix: &str, limit: usize) -> Vec<String> {
let mut cur = self;
for ch in prefix.chars() {
match cur.children.get(&ch) {
Some(next) => cur = next,
None => return Vec::new(),
}
}
let mut out = Vec::new();
let mut buf = String::from(prefix);
cur.collect(&mut buf, limit, &mut out);
out
}
fn collect(&self, buf: &mut String, limit: usize, out: &mut Vec<String>) {
if out.len() >= limit {
return;
}
if self.is_word {
out.push(buf.clone());
}
for (ch, child) in &self.children {
buf.push(*ch);
child.collect(buf, limit, out);
buf.pop();
}
}
}
Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Rust-specific trap
Performance in Rust, beyond the O(m)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Rust type or library should I use for Trie Autocomplete?
No trie in std. The node is a plain struct that owns its children: std::collections::BTreeMap<char, Node> when you want sorted suggestions for free, std::collections::HashMap<char, Node> when order does not matter. Insert is written with the Entry API, children.entry(ch).or_default(), which needs #[derive(Default)] on the node. For a static dictionary the ecosystem answer is the fst crate (finite state transducer, memory-mapped, streams by prefix); for a mutable one, radix_trie or patricia_tree. rustc_hash::FxHashMap replaces the default hasher.
What is the most common Rust mistake when implementing Trie Autocomplete?
The derived Drop glue is recursive: dropping the root drops each child, which drops each grandchild, one stack frame per trie level. Build a trie over long keys (file paths, URLs, DNA reads) and the process aborts with a stack overflow at the closing brace of the function that owned it, thousands of lines from the code that inserted anything. The fix is a manual impl Drop that pops children into a Vec worklist. Second Rust-only trap: &word[..i] panics at a non-char boundary, because slicing is by byte index, so any code that mixes byte offsets with .chars() dies on the first multi-byte character.
How does Trie Autocomplete actually perform in Rust?
std HashMap defaults to SipHash-1-3, a DoS-resistant hash that is dramatically oversized for a 4-byte char key; swapping in FxHashMap or ahash typically halves the descent cost, and a fixed [Option<Box<Node>>; 26] array removes hashing entirely for ASCII alphabets. BTreeMap costs a small binary search per level but hands you sorted iteration with no sort step, which is usually the better trade for autocomplete. The real allocation cost is path.clone() per branch; pass &mut String and truncate on the way back up. Time complexity is O(m) and space is O(n*m).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialIf you are a student, see what Replit offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.