Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Trie Implementation in Rust

14 min readintermediate
Website QA and SEO audits

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 runs in O(m) time and O(n*m) space, in Rust as in every other language.
  • ✓std has no trie. The node is yours: std::collections::HashMap<char, Node> for sparse alphabets, std::collections::BTreeMap<char, Node> when you need sorted prefix enumeration for free, or [Option<Box<Node>>; 26] for a fixed lowercase alphabet.
  • ✓Reviewers expect the iterative descent written as node = node.children.entry(ch).or_default(); the naive if let Some(n) = node.children.get_mut(&ch) inside a loop does not borrow-check, and reaching for Rc<RefCell<Node>> to escape that is the change request everyone writes.
  • ✓The Rust trap: The trie's drop is recursive and the compiler generates it for you: dropping a node drops its HashMap, which drops each child node, which drops its HashMap.
  • ✓HashMap's default hasher is SipHash-1-3, chosen for HashDoS resistance, and hashing a single char is almost entirely fixed setup cost, so per-edge hashing dominates a trie walk.

What Trie actually is

A trie (prefix tree) stores string keys as paths of single-symbol edges: the key lives in the walk from the root, not in any one node, and every node marks whether a key ends there. Lookup, insert and delete are O(m) in the key length with no hashing of the whole key and no collisions. Engineers reach for it when the query is prefix-shaped rather than exact: autocomplete and typeahead, longest-prefix-match routing tables, dictionary/word-break checks, IP and URL prefix rules, and streaming multi-pattern search (Aho-Corasick is a trie plus failure links). A hash map beats it for pure exact lookup; the trie wins the moment you need 'all keys starting with X' or ordered traversal.

Trie in Rust: what you actually reach for

std has no trie. The node is yours: std::collections::HashMap<char, Node> for sparse alphabets, std::collections::BTreeMap<char, Node> when you need sorted prefix enumeration for free, or [Option<Box<Node>>; 26] for a fixed lowercase alphabet. Recursive ownership works because HashMap boxes its table, so a plain struct Node { children: HashMap<char, Node>, is_word: bool } is legal without an explicit Box. Crates worth knowing: radix_trie and qp-trie for general maps, fst for a compiled immutable finite-state map with regex/fuzzy queries, and trie-rs for a LOUDS-succinct trie with common-prefix and incremental search. For the Aho-Corasick case named above, use the aho-corasick crate (BurntSushi) rather than building failure links onto a hand-rolled node.

Rust implementation

Reviewers expect the iterative descent written as node = node.children.entry(ch).or_default(); the naive if let Some(n) = node.children.get_mut(&ch) inside a loop does not borrow-check, and reaching for Rc<RefCell<Node>> to escape that is the change request everyone writes. #[derive(Default)] plus Self::default() over a hand-written new(). Read paths take &self and use the ? operator on get(). Take &str and iterate .chars() or .bytes(), never index the string with a range.
rust
use std::collections::HashMap;

#[derive(Default)]
pub struct Trie {
    children: HashMap<char, Trie>,
    is_word: bool,
}

impl Trie {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn insert(&mut self, word: &str) {
        let mut node = self;
        for ch in word.chars() {
            // reborrow-and-reassign: the only shape the borrow checker accepts
            node = node.children.entry(ch).or_default();
        }
        node.is_word = true;
    }

    fn walk(&self, prefix: &str) -> Option<&Trie> {
        let mut node = self;
        for ch in prefix.chars() {
            node = node.children.get(&ch)?;
        }
        Some(node)
    }

    pub fn contains(&self, word: &str) -> bool {
        matches!(self.walk(word), Some(n) if n.is_word)
    }

    pub fn with_prefix(&self, prefix: &str) -> Vec<String> {
        let mut out = Vec::new();
        let Some(start) = self.walk(prefix) else {
            return out;
        };
        let mut stack = vec![(start, prefix.to_owned())];
        while let Some((node, acc)) = stack.pop() {
            if node.is_word {
                out.push(acc.clone());
            }
            for (ch, child) in &node.children {
                let mut next = acc.clone();
                next.push(*ch);
                stack.push((child, next));
            }
        }
        out
    }
}

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 Free

The Rust-specific trap

The trie's drop is recursive and the compiler generates it for you: dropping a node drops its HashMap, which drops each child node, which drops its HashMap. On a deep trie built from long keys (paths, URLs, genome fragments) that is one stack frame per character and the process aborts with a stack overflow in the destructor, long after every test on short words passed. If keys can be long, write a manual Drop that pops children into a Vec worklist. Related trap: .chars() yields char (a 4-byte scalar), .bytes() yields u8, and mixing them across insert and lookup means a multi-byte key inserted one way is unreachable by the other.

Performance in Rust, beyond the O(m)

HashMap's default hasher is SipHash-1-3, chosen for HashDoS resistance, and hashing a single char is almost entirely fixed setup cost, so per-edge hashing dominates a trie walk. Swapping in rustc_hash::FxHashMap or ahash typically halves the descent. The HashMap variant allocates its table lazily on first insert, so interior nodes cost one heap allocation each and leaves cost none; the [Option<Box<Node>>; 26] variant is 208 bytes of pointer array (Option<Box<T>> is niche-optimised to 8 bytes) plus is_word, so 216 bytes per node whether it has one child or twenty-six, but it is a single indexed load with no hashing and no bounds check when the index is proven in range. Building the whole set into an fst removes both. The asymptotic cost is the same in every language, O(m) time and O(n*m) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Trie between languages.

Real-World Applications

Trie applies wherever its problem shape appears in your own code. In Rust, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Trie helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Trie appears frequently in onsite coding rounds at mid-to-large tech companies. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Trie over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Trie to build pattern recognition. In Rust, demonstrate proficiency with ownership system and pattern matching to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Rust code that is both correct and maintainable.

Frequently Asked Questions

Which Rust type or library should I use for Trie?

std has no trie. The node is yours: std::collections::HashMap<char, Node> for sparse alphabets, std::collections::BTreeMap<char, Node> when you need sorted prefix enumeration for free, or [Option<Box<Node>>; 26] for a fixed lowercase alphabet. Recursive ownership works because HashMap boxes its table, so a plain struct Node { children: HashMap<char, Node>, is_word: bool } is legal without an explicit Box. Crates worth knowing: radix_trie and qp-trie for general maps, fst for a compiled immutable finite-state map with regex/fuzzy queries, and trie-rs for a LOUDS-succinct trie with common-prefix and incremental search. For the Aho-Corasick case named above, use the aho-corasick crate (BurntSushi) rather than building failure links onto a hand-rolled node.

What is the most common Rust mistake when implementing Trie?

The trie's drop is recursive and the compiler generates it for you: dropping a node drops its HashMap, which drops each child node, which drops its HashMap. On a deep trie built from long keys (paths, URLs, genome fragments) that is one stack frame per character and the process aborts with a stack overflow in the destructor, long after every test on short words passed. If keys can be long, write a manual Drop that pops children into a Vec worklist. Related trap: .chars() yields char (a 4-byte scalar), .bytes() yields u8, and mixing them across insert and lookup means a multi-byte key inserted one way is unreachable by the other.

How does Trie actually perform in Rust?

HashMap's default hasher is SipHash-1-3, chosen for HashDoS resistance, and hashing a single char is almost entirely fixed setup cost, so per-edge hashing dominates a trie walk. Swapping in rustc_hash::FxHashMap or ahash typically halves the descent. The HashMap variant allocates its table lazily on first insert, so interior nodes cost one heap allocation each and leaves cost none; the [Option<Box<Node>>; 26] variant is 208 bytes of pointer array (Option<Box<T>> is niche-optimised to 8 bytes) plus is_word, so 216 bytes per node whether it has one child or twenty-six, but it is a single indexed load with no hashing and no bounds check when the index is proven in range. Building the whole set into an fst removes both. Time complexity is O(m) and space is O(n*m).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

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 trial

Studying for this? Student discounts on developer tools are collected on Noizz, tool by tool.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

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.