Chapter 12 - Tries

A tree of characters where words share their prefixes. Search time depends on the length of the word, not on the size of the dictionary.

Coding Interview Patterns book cover with the Rust logo and a CHAP 12 label, the chapter on tries

This page is the entry point of chapter 12 of my Rust solutions to the book Coding Interview Patterns. It sums up the pattern in a few lines, then lists the problems of the chapter. As explained on the series page, the detailed explanations of the algorithms are in the book.

The idea

Each node of a trie has one child per possible next character and a flag that marks the end of a word. Inserting or looking up a word walks down one node per character. Since common prefixes are stored once, a trie can prune a search as soon as a prefix leads nowhere, which is what makes Find All Words on a Board fast.

When to reach for it

  • Prefix questions: autocomplete, “starts with”.
  • Dictionaries with wildcard search.
  • Searching many words at once on a grid, combined with backtracking.

In Rust

  • Children can be a HashMap<char, TrieNode> (any alphabet) or [Option<Box<TrieNode>>; 26] (lowercase letters).
  • With #[derive(Default)] on the node, node.children.entry(c).or_default() walks and creates in one line.
  • Walk the trie iteratively with a &mut cursor: it is simpler than a recursive insert in Rust.

Problems in this chapter

Other chapters

All the chapters, with every problem, are listed on the series page.


Back to top

Published on: Dec 1 2026 at 10:00 AM | Last updated: Dec 1 2026 at 10:32 AM

Copyright © 1964-2026 - 40tude