data structurestrees
trie
a tree of letters where words that share a prefix share a path.
each node stands for a letter, and a word is the path from the root down to a node marked as a word's end. words that start the same share the start of their path.
- insert
- O(L) a node per letter, L letters
- search
- O(L) however many words there are
- starts with
- O(L) a prefix is a path too
- remove
- O(L) unmark, then cut what's left
- memory
- 26 slots per node, nearly all empty
- autocomplete and search suggestions
- spell checkers and word games
- routing tables, which look up the longest matching prefix
- every word with a given prefix, in order
on this page
a trie stores words letter by letter. each node has a slot for every letter, a to z, and a link in a slot leads to the next letter. a word is a path from the root down, with a mark on the node where it ends. words that start the same share the start of the path, so finding a word takes one step per letter, however many words the trie holds.
the idea
an animation in five steps. first car goes into an empty trie: three new nodes, c, a and r, hang in a line under an empty root, and r gets a second outline that marks the end of a word. then cat: the walk follows c and a, which are already there, and only t is new, next to r. then cart: the walk follows c, a and r, and a new t hangs under r, while r keeps its mark, since car is still a word. then the prefix ca: the walk goes down c and a, and everything below a lights up amber, spelling car, cart and cat. last, remove cart: the walk goes down to t, the place to cut moves to r because car ends there, t loses its mark, and t goes.
the easy part
search walks the word one letter at a time: from the root, take the slot for the first letter, then the slot for the next. if a slot is empty, the word isn’t there. if the walk gets to the end, the word is there only if that node is marked. a path with no mark is just a prefix: ca has a path, but no word ends there.
insert is the same walk. where a slot is empty, it makes a new node and keeps going, so the letters a word shares with others cost nothing. at the end, it marks the last node. starts with is the walk without the mark check: if the path exists, some word goes through it.
the operations
tap a node to fill in its prefix.
insert care and count the new nodes. search for ca: its path is there, but no word ends at it. starts with ca lists every word below it. then remove cart, and car.
- nodes looked at
- 0
- nodes
- 9
- words
- 4
insert(t, word): node = t.root for c in word: if node.next[c] is none: node.next[c] = node() # past the part it shares node = node.next[c] if node.word: return false # already here node.word = true return true contains(t, word): node = walk(t, word) return node is not none and node.word with_prefix(t, prefix): node = walk(t, prefix) if node is none: return [] words, stack = [], [(node, prefix)] while stack: node, s = stack.pop() if node.word: words.append(s) for c from z down to a: # so a comes off first if node.next[c]: stack.push((node.next[c], s + c)) return words walk(t, s): node = t.root for c in s: node = node.next[c] if node is none: return none return node remove(t, word): node, cut, at = t.root, t.root, 0 for i, c in enumerate(word): if node is t.root or node.word or children(node) > 1: cut, at = node, i # the last place the path can be cut node = node.next[c] if node is none: return false if not node.word: return false node.word = false if children(node) == 0: cut.next[word[at]] = none # the chain past the cut goes return truean interactive trie that starts with car, cart, cat and dog. each node shows its letter, under an empty root, and a node where a word ends has a second outline. buttons insert, search for or remove a word you type, list the words that start with it, or fill the trie with random words; tapping a node fills in its prefix. a walk tints each link it takes cyan, with a white outline on the node it's at. new nodes show dashed, a prefix search tints everything below the prefix amber and lists the words it finds, and a remove outlines the place it can cut in amber and fades the nodes that go. the matching pseudocode line is highlighted, with counts of the nodes looked at, the nodes and the words. the figure holds 8 branches side by side and words of up to 6 letters.
insert care and count the new nodes: only e. search for ca, then press starts with: the path is there, but no word ends at a. remove cart, then car, and watch where each cut lands.
try it
insert cow. how many new nodes does it add?
pick one.
a practice exercise on a trie. some questions insert a word and ask how many new nodes it adds, or remove one and ask how many nodes go. others ask how many words start with a prefix, or search for a missing word and ask which node the walk stops at, answered by tapping the node.
pseudocode
insert(t, word):
node = t.root
for c in word:
if node.next[c] is none:
node.next[c] = node() # past the part it shares
node = node.next[c]
if node.word: return false # already here
node.word = true
return true
contains(t, word):
node = walk(t, word)
return node is not none and node.word
with_prefix(t, prefix):
node = walk(t, prefix)
if node is none: return []
words, stack = [], [(node, prefix)]
while stack:
node, s = stack.pop()
if node.word: words.append(s)
for c from z down to a: # so a comes off first
if node.next[c]: stack.push((node.next[c], s + c))
return words
walk(t, s):
node = t.root
for c in s:
node = node.next[c]
if node is none: return none
return node
remove(t, word):
node, cut, at = t.root, t.root, 0
for i, c in enumerate(word):
if node is t.root or node.word or children(node) > 1:
cut, at = node, i # the last place the path can be cut
node = node.next[c]
if node is none: return false
if not node.word: return false
node.word = false
if children(node) == 0:
cut.next[word[at]] = none # the chain past the cut goes
return trueevery walk is a loop, here and in every tab. the pseudocode builds each word as s + c to keep it short. the tabs keep one buffer of letters instead, so a long word isn’t copied once per letter.
remove, up close
a prefix of another word
before: remove car
after
cart goes on below car, so only the mark goes
a tail of its own
before: remove seed
after
se branches, so the cut is there: see and seed go
nothing shared
before: remove dog
after
dog shares nothing, so the cut is at the root: all 3 nodes go
three small tries, each shown before and after a remove. removing car from car and cart only takes the mark off r, since cart goes on below it. removing seed from sea, seat and seed cuts at se, where the path branches, and see and seed go. removing dog from car and dog cuts at the root, and all three of dog's nodes go. each case shows before and after side by side. in the first, r is white as it loses its mark; in the other two, the place to cut has an amber outline and the nodes that go are faded.
remove takes the mark off the word’s last node. then it has to clean up: a node that leads to no word is dead weight, and it would make starts with say yes to a prefix nothing has.
- a prefix of another word. words go on below its last node, so every node stays. only the mark goes
- a tail of its own. the nodes past the last branch lead only to this word. walking down, remember the last node that is the root, ends another word, or has another child: that’s where to cut. one link there, set to empty, takes the whole tail with it
- nothing shared. the cut stays at the root, and every node of the word goes
remembering the cut on the way down means remove never walks back up, and needs no list of the nodes it passed.
complexity
| operation | time |
|---|---|
| insert | O(L) |
| search | O(L) |
| starts with | O(L) |
| words with a prefix | O(L + k) |
| remove | O(L) |
L is the length of the word, not the number of words: each of these is one walk down, a step per letter. insert makes a node per letter at most, and remove cuts one link. listing the words with a prefix adds the k nodes below it. a hash table also does a lookup in O(L), since it has to hash every letter, but it can’t answer starts with, and its words don’t come out sorted.
the cost is memory. every node carries 26 slots, and almost all of them are empty: each node but the root sits in exactly one slot of its parent.
the root
the node for ca
- car, cart, cat and dog:
- 9 nodes × 26 = 234 slots, 8 in use (3%)
- the 35 words behind the random button:
- 51 nodes × 26 = 1,326 slots, 50 in use (4%)
two rows of 26 slots, a to z. the root of the trie for car, cart, cat and dog uses only c and d, and the node for ca uses only r and t. below them, the totals: car, cart, cat and dog make 9 nodes, so 234 slots with 8 in use, about 3 in 100; the 35 words behind the random button make 51 nodes, 1,326 slots, with 50 in use, about 4 in 100.
on a 64-bit machine a slot is an 8-byte pointer, so each node costs over 200 bytes, even a node with one child. that’s why real tries keep children in something smaller, or squeeze out the single-child nodes, as the variants below do.
implementations
each tab is the real file from the repo, checked by its tests (go test, cargo test, vitest, make test, swift test, python -m unittest), including 2000 seeded inserts, removes, searches and prefix queries checked against the language’s own set, with the node count checked after every one: one per prefix of a word, plus the root. a word is one or more letters a to z, and anything else is turned away without a change. c hands each word with a prefix to a function you pass in, instead of building a list. go and python leave freeing to their runtimes, but c, rust and swift free nodes in a loop: freeing a node’s children first, then theirs, takes a stack frame per level, and the tests hold a 100,000-letter word.
// Package trie is a reference trie of lowercase words: O(L) insert, lookup and prefix check for a word
// of L letters, however many words it holds. each node has 26 child slots, one per letter, so the words
// come out sorted. every walk is a loop.
package trie
type node struct {
next [26]*node // one slot per letter: next[0] is a, next[25] is z
word bool // a word ends here
}
// children counts the slots that hold a node.
func (n *node) children() int {
count := 0
for _, child := range n.next {
if child != nil {
count++
}
}
return count
}
// isWord reports whether s is one or more letters a to z. It checks bytes, not runes: a to z are
// one byte each, and every byte of any other character falls outside them.
func isWord(s string) bool {
for i := range len(s) {
if s[i] < 'a' || s[i] > 'z' {
return false
}
}
return s != ""
}
// Trie holds words of one or more letters a to z: a word's path from the root spells it, and its
// last node is marked as the end of a word. The zero value is an empty trie, ready to use.
type Trie struct {
root node // a value, not a pointer, so the zero Trie has its root already
size int
nodes int // every node but the root
}
// Len returns how many words are in the trie.
func (t *Trie) Len() int {
return t.size
}
// NodeCount returns how many nodes the trie has, the root included.
func (t *Trie) NodeCount() int {
return t.nodes + 1
}
// find returns the node at the end of s's path, or nil if the path stops short or s isn't all a to z.
func (t *Trie) find(s string) *node {
n := &t.root
for i := range len(s) {
if s[i] < 'a' || s[i] > 'z' {
return nil
}
n = n.next[s[i]-'a']
if n == nil {
return nil
}
}
return n
}
// Insert walks word's letters, making a node for each one past the part it shares, and marks the last.
// It returns false if word is already here or isn't one or more letters a to z.
func (t *Trie) Insert(word string) bool {
if !isWord(word) {
return false // checked up front, so a word that fails leaves no nodes behind
}
n := &t.root
for i := range len(word) {
c := word[i] - 'a'
if n.next[c] == nil {
n.next[c] = &node{}
t.nodes++
}
n = n.next[c]
}
if n.word {
return false
}
n.word = true
t.size++
return true
}
// Contains reports whether word is here: its path exists and its last node is marked as the end of a word.
func (t *Trie) Contains(word string) bool {
n := t.find(word)
return word != "" && n != nil && n.word
}
// HasPrefix reports whether some word starts with prefix. Its path existing is enough: Remove prunes
// every node that leads to no word.
func (t *Trie) HasPrefix(prefix string) bool {
return t.size > 0 && t.find(prefix) != nil
}
// WithPrefix returns the words that start with prefix, sorted: it walks to the prefix's node, then
// collects every word below it.
func (t *Trie) WithPrefix(prefix string) []string {
start := t.find(prefix)
if start == nil {
return nil
}
var out []string
type entry struct {
n *node
depth int
letter int // the slot n hangs from, or -1 for the start, whose letters are in already
}
// the letters of the word being spelled, and a stack of nodes with their depth and letter.
// pushing z first means a comes off first, so the words come out sorted
letters := []byte(prefix)
stack := []entry{{start, len(prefix), -1}}
for len(stack) > 0 {
e := stack[len(stack)-1]
stack = stack[:len(stack)-1]
if e.letter >= 0 {
letters = append(letters[:e.depth-1], byte('a'+e.letter))
}
if e.n.word {
out = append(out, string(letters))
}
for c := 25; c >= 0; c-- {
if child := e.n.next[c]; child != nil {
stack = append(stack, entry{child, e.depth + 1, c})
}
}
}
return out
}
// Remove unmarks word. If its last node has no children, the nodes that led only to it go too:
// everything past the last node on its path that is the root, ends another word, or has another child.
// It returns false if word isn't here.
func (t *Trie) Remove(word string) bool {
if !isWord(word) {
return false
}
// where the path can be cut, and the letter it's cut at
cut, at := &t.root, 0
n := &t.root
for i := range len(word) {
if n == &t.root || n.word || n.children() > 1 {
cut, at = n, i
}
n = n.next[word[i]-'a']
if n == nil {
return false
}
}
if !n.word {
return false
}
n.word = false
t.size--
if n.children() == 0 {
// every node past the cut leads only to this word, so the chain goes with one unhooked link
cut.next[word[at]-'a'] = nil
t.nodes -= len(word) - at
}
return true
}//! trie of lowercase words: O(L) insert, lookup and prefix check for a word of L letters, however many words it holds. each node has 26 child slots, one per letter, so the words come out sorted. every walk is a loop.
#[derive(Default)]
struct Node {
next: [Option<Box<Node>>; 26],
word: bool,
}
impl Node {
/// How many of its slots hold a child.
fn children(&self) -> usize {
self.next.iter().flatten().count()
}
}
/// The slot of each letter in `s`, or `None` if `s` has anything but a to z.
fn slots(s: &str) -> Option<Vec<usize>> {
// collecting Options makes one Option: None if any is None, else Some of them all
s.bytes()
.map(|b| b.is_ascii_lowercase().then(|| usize::from(b - b'a')))
.collect()
}
/// A set of words, each one or more letters a to z, stored one letter per level: slot `c` of a
/// node leads to letter `'a' + c`, and a flag marks the nodes where a word ends. Words that share
/// a prefix share its nodes. The root stands for the empty prefix, so it's always there and counts
/// as a node.
pub struct Trie {
root: Node,
len: usize,
nodes: usize,
}
impl Trie {
/// Makes an empty trie: just the root.
pub fn new() -> Self {
Self {
root: Node::default(),
len: 0,
nodes: 1,
}
}
/// The number of words.
pub fn len(&self) -> usize {
self.len
}
/// Whether there are no words.
pub fn is_empty(&self) -> bool {
self.len == 0
}
/// How many nodes, the root included.
pub fn node_count(&self) -> usize {
self.nodes
}
/// The node at the end of `s`'s path, or `None` if the path stops short or `s` has anything
/// but a to z.
fn find(&self, s: &str) -> Option<&Node> {
let mut node = &self.root;
for c in slots(s)? {
node = node.next[c].as_deref()?;
}
Some(node)
}
/// The node at the end of `path`, which has to be there.
fn node_mut(&mut self, path: &[usize]) -> &mut Node {
let mut node = &mut self.root;
for &c in path {
node = node.next[c].as_deref_mut().expect("the path is there");
}
node
}
/// Walks `word`'s letters, making a node for each one past the part it shares, and marks the
/// last. False if it's already here or isn't one or more letters a to z.
pub fn insert(&mut self, word: &str) -> bool {
let Some(path) = slots(word).filter(|path| !path.is_empty()) else {
return false;
};
let mut node = &mut self.root;
for c in path {
if node.next[c].is_none() {
self.nodes += 1;
}
node = node.next[c].get_or_insert_with(Box::default);
}
if node.word {
return false;
}
node.word = true;
self.len += 1;
true
}
/// Whether `word` is here: its path exists and its last node is marked as the end of a word.
pub fn contains(&self, word: &str) -> bool {
!word.is_empty() && self.find(word).is_some_and(|node| node.word)
}
/// Whether some word starts with `prefix`. Its path existing is enough: remove prunes every
/// node that leads to no word.
pub fn starts_with(&self, prefix: &str) -> bool {
self.len > 0 && self.find(prefix).is_some()
}
/// The words that start with `prefix`, sorted: walk to its node, then collect every word below
/// it.
pub fn with_prefix(&self, prefix: &str) -> Vec<String> {
let mut out = Vec::new();
let Some(start) = self.find(prefix) else {
return out;
};
// the letters of the word being spelled, and a stack of nodes with their depth and letter.
// pushing z first means a comes off first, so the words come out sorted
let mut letters = String::from(prefix);
let mut stack = vec![(start, prefix.len(), None)];
while let Some((node, depth, letter)) = stack.pop() {
if let Some(letter) = letter {
// keep the letters above this node and add its own: one buffer for every word,
// so a long word isn't copied once per letter
letters.truncate(depth - 1);
letters.push(letter);
}
if node.word {
out.push(letters.clone());
}
for c in (0..26).rev() {
if let Some(child) = node.next[c].as_deref() {
stack.push((child, depth + 1, Some(char::from(b'a' + c as u8))));
}
}
}
out
}
/// Unmarks `word`. If its last node has no children, the nodes that led only to it go too:
/// everything past the last node on its path that is the root, ends another word, or has
/// another child. False if it isn't here.
pub fn remove(&mut self, word: &str) -> bool {
let Some(path) = slots(word).filter(|path| !path.is_empty()) else {
return false;
};
// the borrow checker won't let a walk hold a `&mut` to the cut node while it goes on
// below it, so this takes two walks. the first only looks
let mut cut = 0; // the letter where the path can be cut
let mut node = &self.root;
for (i, &c) in path.iter().enumerate() {
// node sits above letter i, so it's the root when i is 0
if i == 0 || node.word || node.children() > 1 {
cut = i;
}
let Some(next) = node.next[c].as_deref() else {
return false;
};
node = next;
}
if !node.word {
return false;
}
let prune = node.children() == 0;
// the second walk makes the change
self.len -= 1;
if prune {
// every node past the cut leads only to this word, so the chain goes with one
// unhooked link
self.node_mut(&path[..cut]).next[path[cut]] = None;
self.nodes -= path.len() - cut;
} else {
self.node_mut(&path).word = false;
}
true
}
}
impl Default for Trie {
fn default() -> Self {
Self::new()
}
}
/// The default drop would free a node's children, whose drops free their children, and so on:
/// one stack frame per level, so a long word overflows the stack. This one moves the children
/// onto a stack of its own, a `Vec`. Each node it pops hands its children over too, so it drops
/// with every slot empty, and its own drop has nothing to free. It's on `Node`, not `Trie`, so it
/// covers a chain that remove unhooks as well as a whole trie.
impl Drop for Node {
fn drop(&mut self) {
let mut stack: Vec<Box<Node>> = self.next.iter_mut().filter_map(Option::take).collect();
while let Some(mut node) = stack.pop() {
stack.extend(node.next.iter_mut().filter_map(Option::take));
// its slots are empty now, so it drops here on its own
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeSet;
fn from<'a>(words: impl IntoIterator<Item = &'a str>) -> Trie {
let mut t = Trie::new();
for w in words {
t.insert(w);
}
t
}
// car, cart and cat share c-a, and dog shares nothing: 8 nodes and the root
const WORDS: [&str; 4] = ["car", "cat", "cart", "dog"];
#[test]
fn starts_empty_just_the_root() {
let mut t = Trie::new();
assert!(t.is_empty());
assert_eq!(
(
t.len(),
t.node_count(),
t.contains("a"),
t.starts_with(""),
t.with_prefix(""),
t.remove("a")
),
(0, 1, false, false, vec![], false)
);
}
#[test]
fn words_that_share_a_prefix_share_its_nodes() {
let mut t = Trie::new();
assert_eq!((t.insert("car"), t.node_count()), (true, 4));
// cat shares c-a and adds t; cart goes on past car; dog shares nothing
assert_eq!((t.insert("cat"), t.node_count()), (true, 5));
assert_eq!((t.insert("cart"), t.node_count()), (true, 6));
assert_eq!((t.insert("dog"), t.node_count()), (true, 9));
assert_eq!(t.len(), 4);
assert_eq!(t.with_prefix(""), ["car", "cart", "cat", "dog"]);
}
#[test]
fn a_word_that_is_already_there_or_has_anything_but_a_to_z_changes_nothing() {
let mut t = from(WORDS);
assert_eq!(
["cat", "Cat", "c-t", "", "café"].map(|w| t.insert(w)),
[false; 5]
);
assert_eq!((t.len(), t.node_count()), (4, 9));
}
#[test]
fn contains_wants_a_whole_word_starts_with_takes_any_prefix() {
let t = from(WORDS);
assert!(WORDS.into_iter().all(|w| t.contains(w)));
assert!(
["c", "ca", "do", "cars", "cow", "", "Car"]
.into_iter()
.all(|w| !t.contains(w))
);
assert!(
["", "c", "ca", "car", "cart", "d", "dog"]
.into_iter()
.all(|p| t.starts_with(p))
);
assert!(
["x", "cb", "carts", "dogs", "D"]
.into_iter()
.all(|p| !t.starts_with(p))
);
}
#[test]
fn with_prefix_walks_to_the_prefix_then_collects_every_word_below_it_sorted() {
let t = from(WORDS);
assert_eq!(t.with_prefix("ca"), ["car", "cart", "cat"]);
assert_eq!(t.with_prefix("car"), ["car", "cart"]);
assert_eq!(t.with_prefix("dog"), ["dog"]);
assert!(
["x", "dogs", "C"]
.into_iter()
.all(|p| t.with_prefix(p).is_empty())
);
}
#[test]
fn the_words_come_out_sorted_whatever_order_they_went_in() {
let t = from(["dot", "do", "apple", "ape", "dog", "a", "zoo", "app"]);
assert_eq!(
t.with_prefix(""),
["a", "ape", "app", "apple", "do", "dog", "dot", "zoo"]
);
}
#[test]
fn remove_a_word_that_is_a_prefix_of_another_only_its_mark_goes() {
let mut t = from(WORDS);
assert_eq!(
(
t.remove("car"),
t.node_count(),
t.contains("car"),
t.contains("cart")
),
(true, 9, false, true)
);
}
#[test]
fn remove_a_word_with_its_own_tail_prune_back_to_the_branch() {
let mut t = from(WORDS);
assert_eq!((t.remove("cart"), t.node_count()), (true, 8));
assert_eq!(t.with_prefix(""), ["car", "cat", "dog"]);
// cat's t goes too, and a stays for car
assert_eq!((t.remove("cat"), t.node_count()), (true, 7));
}
#[test]
fn remove_a_word_that_shares_nothing_prune_to_the_root() {
let mut t = from(WORDS);
assert_eq!(
(t.remove("dog"), t.node_count(), t.starts_with("d")),
(true, 6, false)
);
}
#[test]
fn a_prefix_that_is_not_a_word_or_a_missing_word_does_not_come_out() {
let mut t = from(WORDS);
assert_eq!(
["ca", "cars", "cow", "", "Cat"].map(|w| t.remove(w)),
[false; 5]
);
assert_eq!((t.len(), t.node_count()), (4, 9));
}
#[test]
fn remove_every_word_and_only_the_root_is_left() {
let mut t = from(WORDS);
for w in WORDS {
t.remove(w);
}
assert_eq!(
(
t.len(),
t.node_count(),
t.starts_with(""),
t.with_prefix("")
),
(0, 1, false, vec![])
);
}
#[test]
fn a_word_of_100000_letters_every_walk_is_a_loop() {
let long = "ab".repeat(50_000);
let mut t = from([long.as_str(), "abc"]);
assert_eq!(
(t.len(), t.node_count(), t.contains(&long)),
(2, 100_002, true)
);
assert_eq!(t.with_prefix("ab"), [long.as_str(), "abc"]);
// abc keeps a and b
assert_eq!((t.remove(&long), t.node_count()), (true, 4));
// the chain remove unhooked dropped without recursion, and so does a whole trie that
// holds the word. a drop that took a stack frame per letter would overflow the 2 MB stack
// a test thread gets
assert!(t.insert(&long));
drop(t);
}
#[test]
fn agrees_with_a_set_over_2000_seeded_operations() {
// xorshift32 seeded with 42, like the other tests here
let mut state: u32 = 42;
let mut next = || {
state ^= state << 13;
state ^= state >> 17;
state ^= state << 5;
state as usize
};
let mut t = Trie::new();
let mut model = BTreeSet::new();
for _ in 0..2000 {
// 1 to 4 letters from a to d, so words share prefixes and come up again
let len = 1 + next() % 4;
let w: String = (0..len).map(|_| char::from(b"abcd"[next() % 4])).collect();
let prefix = &w[..next() % (len + 1)];
match next() % 5 {
0 => assert_eq!(t.insert(&w), model.insert(w.clone())),
1 => assert_eq!(t.remove(&w), model.remove(&w)),
2 => assert_eq!(t.contains(&w), model.contains(&w)),
3 => assert_eq!(
t.starts_with(prefix),
model.iter().any(|x| x.starts_with(prefix))
),
_ => assert_eq!(
t.with_prefix(prefix),
model
.iter()
.filter(|x| x.starts_with(prefix))
.cloned()
.collect::<Vec<_>>()
),
}
assert_eq!(t.len(), model.len());
// a node for every prefix of every word, plus the root: a remove leaves nothing behind
let prefixes: BTreeSet<&str> = model
.iter()
.flat_map(|x| (1..=x.len()).map(move |i| &x[..i]))
.collect();
assert_eq!(t.node_count(), prefixes.len() + 1);
}
}
}/**
* Trie of lowercase words: O(L) insert, lookup and prefix check for a word of L letters, however many words it
* holds. Each node has 26 child slots, one per letter, so the words come out sorted. Every walk is a loop.
*/
type Node = { next: (Node | null)[]; word: boolean };
const A = 97; // 'a'
const node = (): Node => ({ next: Array<Node | null>(26).fill(null), word: false });
const children = (n: Node) => n.next.filter((child) => child !== null).length;
/** The slot of each letter in s, or null if s has anything but a to z. */
function slots(s: string): number[] | null {
const out: number[] = [];
for (let i = 0; i < s.length; i++) {
const c = s.charCodeAt(i) - A;
if (c < 0 || c > 25) return null;
out.push(c);
}
return out;
}
export class Trie {
#root = node();
#size = 0;
#nodes = 1;
/** How many words. */
get size(): number {
return this.#size;
}
/** How many nodes, the root included. */
get nodeCount(): number {
return this.#nodes;
}
/** The node at the end of s's path, or null if the path stops short. */
#find(s: string): Node | null {
const path = slots(s);
if (!path) return null;
let n: Node | null = this.#root;
for (const c of path) {
n = n.next[c];
if (!n) return null;
}
return n;
}
/** Walk word's letters, making a node for each one past the part it shares, and mark the last. False if it's
* already here or isn't one or more letters a to z. */
insert(word: string): boolean {
const path = slots(word);
if (!path?.length) return false;
let n = this.#root;
for (const c of path) {
if (!n.next[c]) {
n.next[c] = node();
this.#nodes += 1;
}
n = n.next[c]!;
}
if (n.word) return false;
n.word = true;
this.#size += 1;
return true;
}
/** Whether word is here: its path exists and its last node is marked as the end of a word. */
contains(word: string): boolean {
return word.length > 0 && (this.#find(word)?.word ?? false);
}
/** Whether some word starts with prefix. Its path existing is enough: remove prunes every node that leads to no
* word. */
startsWith(prefix: string): boolean {
return this.#size > 0 && this.#find(prefix) !== null;
}
/** The words that start with prefix, sorted: walk to its node, then collect every word below it. */
withPrefix(prefix: string): string[] {
const start = this.#find(prefix);
if (!start) return [];
const out: string[] = [];
// the letters of the word being spelled, and a stack of nodes with their depth and letter. pushing z first
// means a comes off first, so the words come out sorted
const letters = [...prefix];
const stack: [Node, number, number][] = [[start, letters.length, -1]];
while (stack.length) {
const [n, depth, c] = stack.pop()!;
if (c >= 0) {
letters.length = depth - 1;
letters.push(String.fromCharCode(A + c));
}
if (n.word) out.push(letters.join(''));
for (let k = 25; k >= 0; k--) {
const child = n.next[k];
if (child) stack.push([child, depth + 1, k]);
}
}
return out;
}
/** Unmark word. If its last node has no children, the nodes that led only to it go too: everything past the last
* node on its path that is the root, ends another word, or has another child. False if it isn't here. */
remove(word: string): boolean {
const path = slots(word);
if (!path?.length) return false;
// where the path can be cut, and the letter it's cut at
let cut = this.#root;
let at = 0;
let n = this.#root;
for (let i = 0; i < path.length; i++) {
if (n === this.#root || n.word || children(n) > 1) {
cut = n;
at = i;
}
const next = n.next[path[i]];
if (!next) return false;
n = next;
}
if (!n.word) return false;
n.word = false;
this.#size -= 1;
if (children(n) === 0) {
// every node past the cut leads only to this word, so the chain goes with one unhooked link
cut.next[path[at]] = null;
this.#nodes -= path.length - at;
}
return true;
}
}/* trie of lowercase words: O(L) insert, lookup and prefix check for a word of L letters, however many words it holds. each node has 26 child slots, one per letter, so the words come out sorted. every walk is a loop. */
#include "trie.h"
#include <stdlib.h>
#include <string.h>
/* letter ch's slot, or -1 if ch isn't a to z */
static int slot(char ch) {
return ch >= 'a' && ch <= 'z' ? ch - 'a' : -1;
}
/* true if s is one or more letters a to z */
static bool is_word(const char *s) {
if (!*s) return false;
for (; *s; s++) {
if (slot(*s) < 0) return false;
}
return true;
}
/* how many of n's slots lead somewhere */
static int children(const TrieNode *n) {
int count = 0;
for (int c = 0; c < 26; c++) count += n->next[c] != NULL;
return count;
}
/* n's lowest slot that isn't NULL, or -1 if they all are */
static int lowest(const TrieNode *n) {
for (int c = 0; c < 26; c++) {
if (n->next[c]) return c;
}
return -1;
}
/* the node at the end of s's path, or NULL if the path stops short or s has anything but a to z */
static const TrieNode *find(const Trie *t, const char *s) {
const TrieNode *n = &t->root;
for (; *s; s++) {
int c = slot(*s);
if (c < 0 || !n->next[c]) return NULL;
n = n->next[c];
}
return n;
}
/* frees a chain of nodes that each have one child, down to the last one, which has none */
static void free_chain(TrieNode *n) {
while (n) {
int c = lowest(n);
TrieNode *next = c < 0 ? NULL : n->next[c];
free(n);
n = next;
}
}
void trie_init(Trie *t) {
*t = (Trie){.nodes = 1}; /* every slot NULL and no words: just the root */
}
/* pointer reversal: the way back up is kept in the slots themselves, so there's no recursion and
no stack. going down from a node into its lowest child, the node's parent goes in that child's
slot. coming back up to a node, its lowest non-empty slot holds its parent (every slot below it
is already empty), so take it, clear the slot, and go down the next child. a node with no
children left is freed, and the walk goes back to its parent. the root stays (it lives in t),
and stands in as its own parent, since a NULL parent would look like an empty slot */
void trie_free(Trie *t) {
TrieNode *root = &t->root, *n = root, *up = root;
for (;;) {
int c = lowest(n);
if (c >= 0) {
TrieNode *down = n->next[c];
n->next[c] = up; /* the way back up from n */
up = n;
n = down;
} else if (n == root) {
break; /* every node below it is gone */
} else {
free(n);
n = up;
c = lowest(n); /* holds n's parent */
up = n->next[c];
n->next[c] = NULL;
}
}
trie_init(t);
}
bool trie_insert(Trie *t, const char *word, bool *added) {
*added = false;
if (!is_word(word)) return true; /* empty, or not all a to z: nothing changes */
TrieNode *n = &t->root;
const char *p = word;
for (; *p && n->next[slot(*p)]; p++) n = n->next[slot(*p)]; /* the part already here */
/* a node for each letter past it. they hang in one chain off branch, at rest's first letter,
so if a node can't be allocated, unhooking that chain and freeing it undoes this call */
TrieNode *branch = n;
const char *rest = p;
for (; *p; p++) {
TrieNode *made = calloc(1, sizeof *made); /* calloc: every slot NULL, and word false */
if (!made) {
free_chain(branch->next[slot(*rest)]);
branch->next[slot(*rest)] = NULL;
return false;
}
n->next[slot(*p)] = made;
n = made;
}
t->nodes += (size_t)(p - rest);
if (n->word) return true; /* already here */
n->word = true;
t->len++;
*added = true;
return true;
}
bool trie_contains(const Trie *t, const char *word) {
const TrieNode *n = find(t, word);
return *word && n && n->word;
}
/* the path existing is enough: remove frees every node that leads to no word */
bool trie_has_prefix(const Trie *t, const char *prefix) {
return t->len > 0 && find(t, prefix) != NULL;
}
/* a node the walk has yet to visit: how many letters deep it is, and the letter that leads to it
(-1 for the prefix's own node, whose letters are already in place) */
typedef struct {
const TrieNode *node;
size_t depth;
int letter;
} Pending;
/* walk to the prefix's node, then collect every word below it with a stack instead of recursion.
children go on z first, so a comes off first and the words come out sorted. letters spells the
word at the node being visited, indexed by depth: each node writes only its own letter, since
the letters of the nodes above it are already in place. copying a string per node instead would
make a word of L letters cost O(L^2) */
bool trie_with_prefix(const Trie *t, const char *prefix, void (*visit)(const char *word, void *ctx),
void *ctx) {
const TrieNode *start = find(t, prefix);
if (!start) return true; /* no word starts with it */
size_t len = strlen(prefix), letters_cap = len + 16, stack_cap = 16, top = 0;
char *letters = malloc(letters_cap);
Pending *stack = malloc(stack_cap * sizeof *stack);
bool ok = letters && stack;
if (ok) {
memcpy(letters, prefix, len);
stack[top++] = (Pending){start, len, -1};
}
while (ok && top > 0) {
Pending p = stack[--top];
/* room for depth letters and a nul. a node is one letter deeper than the node that pushed
it, so doubling once is enough */
if (p.depth >= letters_cap) {
char *bigger = realloc(letters, 2 * letters_cap);
if (!bigger) {
ok = false;
break;
}
letters = bigger;
letters_cap *= 2;
}
if (p.letter >= 0) letters[p.depth - 1] = (char)('a' + p.letter);
if (p.node->word) {
letters[p.depth] = '\0';
visit(letters, ctx);
}
for (int c = 25; c >= 0; c--) {
if (!p.node->next[c]) continue;
if (top == stack_cap) {
Pending *bigger = realloc(stack, 2 * stack_cap * sizeof *stack);
if (!bigger) {
ok = false;
break;
}
stack = bigger;
stack_cap *= 2;
}
stack[top++] = (Pending){p.node->next[c], p.depth + 1, c};
}
}
free(letters);
free(stack);
return ok;
}
/* walk the path, remembering the last place it can be cut: the last node before the word's end
that is the root, ends another word, or has another child. every node past it leads only to
this word, so if the end has no children, that whole chain goes with one unhooked link */
bool trie_remove(Trie *t, const char *word) {
if (!is_word(word)) return false;
TrieNode *n = &t->root;
size_t i = 0;
/* where the path can be cut, and the index of the letter it's cut at */
TrieNode *cut = n;
size_t at = 0;
for (; word[i]; i++) {
if (n == &t->root || n->word || children(n) > 1) {
cut = n;
at = i;
}
n = n->next[slot(word[i])];
if (!n) return false; /* the path stops short */
}
if (!n->word) return false; /* a prefix of other words, but not a word itself */
n->word = false;
t->len--;
if (children(n) == 0) {
TrieNode *chain = cut->next[slot(word[at])];
cut->next[slot(word[at])] = NULL;
free_chain(chain);
t->nodes -= i - at; /* one node per letter from at to the end */
}
return true;
}/// trie of lowercase words: O(L) insert, lookup and prefix check for a word of L letters, however many words it holds. each node has 26 child slots, one per letter, so the words come out sorted. every walk is a loop.
/// a class, since its nodes are shared references: copying a struct around them wouldn't copy the trie. its nodes also need a deinit, to free a long word's chain in a loop.
public final class Trie {
final class Node {
var next: [Node?] = Array(repeating: nil, count: 26) // slot c is the letter "a" + c
var word = false // a word ends here
var children: Int { next.count(where: { $0 != nil }) }
// releasing a node would release its children from inside that release, and theirs from inside those: one
// stack frame per letter, enough to crash on a long word, when the trie goes away or remove unhooks a chain.
// put the children on a stack instead, and empty each one's slots before it's released: then it's freed
// with no children of its own to release
deinit {
var stack = next.compactMap { $0 }
while let node = stack.popLast() {
for c in 0..<26 {
if let child = node.next[c] {
stack.append(child)
node.next[c] = nil
}
}
}
}
}
private let root = Node()
/// how many words
public private(set) var count = 0
/// how many nodes, the root included
public private(set) var nodeCount = 1
public init() {}
/// walks word's letters, making a node for each one past the part it shares, and marks the last. false if it's
/// already here or isn't one or more letters a to z
@discardableResult
public func insert(_ word: String) -> Bool {
guard let path = slots(word), !path.isEmpty else { return false }
var node = root
for c in path {
if node.next[c] == nil {
node.next[c] = Node()
nodeCount += 1
}
node = node.next[c]!
}
if node.word { return false }
node.word = true
count += 1
return true
}
/// whether word is here: its path exists and its last node is marked as the end of a word
public func contains(_ word: String) -> Bool {
!word.isEmpty && (find(word)?.word ?? false)
}
/// whether some word starts with prefix: there's a word at all, and the prefix's path exists. the path is
/// enough, since remove prunes every node that leads to no word
public func hasPrefix(_ prefix: String) -> Bool {
count > 0 && find(prefix) != nil
}
/// the words that start with prefix, sorted: walk to its node, then collect every word below it
public func withPrefix(_ prefix: String) -> [String] {
guard let start = find(prefix) else { return [] }
var out: [String] = []
// the letters of the word being spelled, and a stack of nodes with their depth and letter (nil for the
// prefix's node). one buffer instead of a string per node keeps a long word O(L). pushing z first means a
// comes off first, so the words come out sorted
var letters = Array(prefix.utf8)
var stack: [(node: Node, depth: Int, letter: Int?)] = [(start, letters.count, nil)]
while let (node, depth, letter) = stack.popLast() {
if let letter {
// keep the letters that lead to its parent, then add its own
letters.removeSubrange((depth - 1)...)
letters.append(UInt8(ascii: "a") + UInt8(letter))
}
if node.word { out.append(String(decoding: letters, as: UTF8.self)) }
for c in (0..<26).reversed() {
if let child = node.next[c] { stack.append((child, depth + 1, c)) }
}
}
return out
}
/// unmarks word. if its last node has no children, the nodes that led only to it go too: everything past the
/// last node on its path that is the root, ends another word, or has another child. false if it isn't here
@discardableResult
public func remove(_ word: String) -> Bool {
guard let path = slots(word), !path.isEmpty else { return false }
// where the path can be cut, and the letter it's cut at
var cut = root
var at = 0
var node = root
for (i, c) in path.enumerated() {
if node === root || node.word || node.children > 1 {
cut = node
at = i
}
guard let child = node.next[c] else { return false }
node = child
}
guard node.word else { return false }
node.word = false
count -= 1
if node.children == 0 {
// every node past the cut leads only to this word, so the chain goes with one unhooked link
cut.next[path[at]] = nil
nodeCount -= path.count - at
}
return true
}
/// the node at the end of s's path, or nil if the path stops short
private func find(_ s: String) -> Node? {
guard let path = slots(s) else { return nil }
var node = root
for c in path {
guard let child = node.next[c] else { return nil }
node = child
}
return node
}
/// the slot of each letter in s, or nil if s has anything but a to z
private func slots(_ s: String) -> [Int]? {
let a = UInt8(ascii: "a")
let z = UInt8(ascii: "z")
var out: [Int] = []
// utf-8 bytes: a letter like é takes two, and neither is a to z
for byte in s.utf8 {
guard a <= byte && byte <= z else { return nil }
out.append(Int(byte - a))
}
return out
}
}"""trie of lowercase words: O(L) insert, lookup and prefix check for a word of L letters, however many words it holds. each node has 26 child slots, one per letter, so the words come out sorted. every walk is a loop."""
from __future__ import annotations
class _Node:
__slots__ = ("next", "word")
def __init__(self) -> None:
self.next: list[_Node | None] = [None] * 26 # one slot per letter: next[0] is a, next[25] is z
self.word = False # a word ends here
def _slots(s: str) -> list[int] | None:
"""Return the slot of each letter in s, or None if s has anything but a to z."""
out: list[int] = []
for ch in s:
if not "a" <= ch <= "z":
return None
out.append(ord(ch) - ord("a"))
return out
def _children(node: _Node) -> int:
return len(node.next) - node.next.count(None)
class Trie:
"""Words of one or more letters a to z.
A word's path from the root spells it, and its last node is marked as the end of a word.
"""
def __init__(self) -> None:
self._root = _Node() # always here, even with no words
self._size = 0
self._nodes = 1 # the root counts
def __len__(self) -> int:
return self._size
def node_count(self) -> int:
"""Return how many nodes there are, the root included."""
return self._nodes
def insert(self, word: str) -> bool:
"""Walk word's letters, making a node for each one past the part it shares, and mark the last.
Return False if it's already here or isn't one or more letters a to z.
"""
path = _slots(word)
if not path:
return False
node = self._root
for c in path:
child = node.next[c]
if child is None:
child = _Node()
node.next[c] = child
self._nodes += 1
node = child
if node.word:
return False
node.word = True
self._size += 1
return True
def __contains__(self, word: str) -> bool:
"""Walk word's path: it's here if the path exists and its last node is marked."""
node = self._find(word)
return word != "" and node is not None and node.word
def starts_with(self, prefix: str) -> bool:
"""Return True if some word starts with prefix.
Its path existing is enough: remove prunes every node that leads to no word.
"""
return self._size > 0 and self._find(prefix) is not None
def with_prefix(self, prefix: str) -> list[str]:
"""Return the words that start with prefix, sorted.
Walk to the prefix's node, then collect every word below it.
"""
start = self._find(prefix)
if start is None:
return []
out: list[str] = []
# the letters of the word being spelled, and a stack of nodes with their depth and letter.
# pushing z first means a comes off first, so the words come out sorted
letters = list(prefix)
stack = [(start, len(letters), -1)] # -1: the start's letters are in already
while stack:
node, depth, c = stack.pop()
if c >= 0:
del letters[depth - 1 :]
letters.append(chr(ord("a") + c))
if node.word:
out.append("".join(letters))
for k in range(25, -1, -1):
child = node.next[k]
if child is not None:
stack.append((child, depth + 1, k))
return out
def remove(self, word: str) -> bool:
"""Unmark word. Return False if it isn't here.
If its last node has no children, the nodes that led only to it go too: everything past the last
node on its path that is the root, ends another word, or has another child.
"""
path = _slots(word)
if not path:
return False
# where the path can be cut, and the letter it's cut at
cut, at = self._root, 0
node = self._root
for i, c in enumerate(path):
if node is self._root or node.word or _children(node) > 1:
cut, at = node, i
child = node.next[c]
if child is None:
return False
node = child
if not node.word:
return False
node.word = False
self._size -= 1
if _children(node) == 0:
# every node past the cut leads only to this word, so the chain goes with one unhooked link
cut.next[path[at]] = None
self._nodes -= len(path) - at
return True
def _find(self, s: str) -> _Node | None:
"""Return the node at the end of s's path, or None if the path stops short or s isn't all a to z."""
path = _slots(s)
if path is None:
return None
node = self._root
for c in path:
child = node.next[c]
if child is None:
return None
node = child
return nodepitfalls
- a path isn’t a word. search has to check the mark at the end. without it, every prefix of every word counts as a word
- remove without the cut. taking off the mark and stopping there leaves dead nodes behind: memory that never comes back, and a starts with that answers yes for prefixes no word has
- the alphabet. 26 slots means a to z and nothing else. capitals, digits, spaces or other scripts need more slots, or children kept in a map
- deep words, deep recursion. a word of n letters is a path n nodes deep. a recursive walk or free takes a stack frame per letter
- memory. each node holds 26 slots whether it uses one or all of them. for many words with little in common, a hash table can be smaller
variants
- children in a map. a hash map or a sorted list per node holds only the letters that are there. any alphabet works, and memory follows the children, at the cost of a lookup per step
- radix tree. a run of nodes with one child each becomes one node that holds the string. an insert may split such a node, and a remove may merge a run back together. redis keeps its streams in one1
- ternary search tree. each node holds one letter and three links: smaller letters, the next letter, bigger letters. a small binary search tree at every level, in place of 26 slots
- bitwise tries. the alphabet is 0 and 1, and a key’s bits spell the path. routing tables use them to find the longest prefix that matches an address. the linux kernel’s ipv4 routing table is one2
- hash tries. spell the path with the bits of each key’s hash instead of its letters, and any key works. swift-collections’
TreeSetandTreeDictionaryare built this way3 - suffix tries. insert every suffix of one text, and any substring is a prefix of some suffix: searching for a pattern is a walk of its letters
practice
- implement trie (prefix tree) (opens in a new tab): insert, search and starts with
- design add and search words data structure (opens in a new tab): a dot matches any letter, so the walk branches
- replace words (opens in a new tab): the shortest word that is a prefix
- longest word in dictionary (opens in a new tab): the deepest path where every node ends a word
- search suggestions system (opens in a new tab): the first three words below each prefix
- word search ii (opens in a new tab): walk a grid and the trie together
how real systems do it
- redis.
raxis a radix tree: runs of single-child nodes are packed into one, and nodes split and merge as keys come and go. a stream is stored in one1 - linux. the ipv4 routing table is a bitwise trie with level and path compression, an lpc-trie after work by nilsson, tikkanen and karlsson, and a lookup travels to the longest matching prefix2
- swift. swift-collections’
TreeSetandTreeDictionaryare compressed hash-array mapped prefix trees, champ for short: tries over hash bits that can share their nodes between copies3 - the standard libraries. python, go, rust, java and swift have no trie in theirs. a map of words, or a sorted list, covers most uses
sources
-
rax.h (opens in a new tab) in redis 8.10.2: a radix tree where nodes with a single child, one after another, are compressed into one node that holds their characters. adding a key can split a compressed node, and a delete that leaves a chain of single-child nodes compresses it back. in stream.h (opens in a new tab), a stream is held in a radix tree. ↩ ↩2
-
fib_trie.c (opens in a new tab) in linux 7.2: based on the lpc-trie described by nilsson and tikkanen (2002), and on ip-address lookup with lc-tries by nilsson and karlsson (1999). its
fib_table_lookup(opens in a new tab) starts by traveling to the longest prefix match in the trie. ↩ ↩2 -
readme (opens in a new tab) of swift-collections 1.7.3:
TreeSetandTreeDictionaryare persistent hashed collections implementing compressed hash-array mapped prefix trees (champ), which mutate shared copies without duplicating the unchanged parts. ↩ ↩2