Trie-based string processing
Intermediate · 10 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
A trie stores many words as a tree where words sharing the same beginning share the same branch. To find everything starting with "ca", you walk down c then a and collect what hangs below. The work depends on the length of what was typed, not on how many words are stored.
Practical use cases
- Web app: Autocomplete in a food delivery search bar. A user types "bir" in a restaurant app and expects "biryani", "birria tacos" and "bird nest soup" instantly. Scanning 50,000 dish names on every keystroke lags. A trie walks three steps (b, i, r) and lists the words below, so suggestions appear as fast as the finger moves.
- Web app: City picker on a checkout form. A checkout form asks for a city. As the user types, the page narrows the list of 20,000 Indian towns by prefix. The trie keeps the matching branch ready, so the dropdown updates after every key without a new request to the server.
- System: Spell checkers and IP routing. Spell checkers and word games keep the dictionary in a trie to quickly ask "is this a word?" and "does any word start like this?". Network routers also match an address against route prefixes the same way, following the longest matching branch.
The story: The Phone That Finished Your Sentences
Kabir got his first phone, and the contact list had 500 names. When he typed "ca", the phone instantly showed Cat Auntie, Car Wala Uncle and Carrom Club. Kabir was amazed. "How does it find all names starting with ca so fast? Does it read all 500 every time?"
Mira drew a tree on the back of a notebook. "Imagine a tree where each branch is a letter. All names that start with C hang from the C branch. Under C, the ones with A hang from the A branch, and so on. To find all words that start with 'ca', just walk down C, then A, and look at everything hanging below."
Kabir tried it with CAT, CAR, DOG and DO. CAT and CAR shared the C-A branch, saving effort. DO and DOG shared D-O. He noticed that finding a prefix took as many steps as the prefix has letters, no matter whether the phone held 500 words or 5 million. This letter tree is called a trie (say "try"), and it is the engine behind autocomplete, spell check and word games.
How to spot this problem, and where you need it
You have a large set of words and constantly need to find the ones that start with whatever the user has typed so far, and scanning the entire list for each keystroke is too slow.
Signs you need it
- A feature uses "starts with", "prefix", "autocomplete", "type-ahead" or "suggestions" and runs on every keystroke.
- Your code loops over all words and calls startsWith on each one, and it lags as the word list grows.
- You need to know whether any word begins with a given text, such as pruning a word-game search early.
Where to use it in a project
- Search boxes for products, restaurants, cities, usernames or tags in a web or mobile app.
- Word games and form validators that must quickly reject impossible letter combinations.
- Routing tables and command palettes that match the longest known prefix.
The solution
Build a tree where each step down is one letter. Insert each word by following or creating its letters and marking where a word ends. To suggest, walk down the typed letters; if you fall off the tree, there are no matches. Otherwise collect the words under that node, optionally only the top few. The walk costs about the number of letters typed.
Payoff: Before: checking 50,000 names per keystroke. After: about 3 steps plus reading a few suggestions, so the dropdown feels instant.
Explain it like I am 8
It is like a big family tree of words. Every word starts at the same grandparent (the root). Words that begin with the same letters share the same branches. To find all words that start with "ca", walk down the C branch, then the A branch, and everything under it is an answer.
How it works, step by step
- Start with an empty root node that has no letters.
- To insert a word, walk letter by letter from the root. If a branch for the letter is missing, create it.
- At the last letter, mark the node "a word ends here" (so DO is a word even though DOG continues).
- To look up a prefix, walk down its letters. If any branch is missing, no word starts with it.
- To autocomplete, after reaching the prefix node, collect every marked word below it by exploring its branches.
The code in four languages
PHP
<?php
class TrieNode {
public array $kids = []; // letter => TrieNode
public bool $end = false; // does a word finish here?
}
class Trie {
private TrieNode $root;
public function __construct() { $this->root = new TrieNode(); }
public function insert(string $word): void {
$node = $this->root;
for ($i = 0; $i < strlen($word); $i++) {
$ch = $word[$i];
if (!isset($node->kids[$ch])) {
$node->kids[$ch] = new TrieNode(); // grow a new branch
}
$node = $node->kids[$ch];
}
$node->end = true; // a word ends here
}
// Walk down the prefix; return the node, or null if it does not exist.
private function find(string $prefix): ?TrieNode {
$node = $this->root;
for ($i = 0; $i < strlen($prefix); $i++) {
$node = $node->kids[$prefix[$i]] ?? null;
if ($node === null) { return null; }
}
return $node;
}
public function startsWith(string $prefix): bool {
return $this->find($prefix) !== null;
}
// Autocomplete: all words below the prefix node.
public function complete(string $prefix): array {
$node = $this->find($prefix);
$out = [];
if ($node !== null) { $this->collect($node, $prefix, $out); }
return $out;
}
private function collect(TrieNode $node, string $path, array &$out): void {
if ($node->end) { $out[] = $path; }
foreach ($node->kids as $ch => $child) {
$this->collect($child, $path . $ch, $out);
}
}
}
$t = new Trie();
foreach (["cat", "car", "dog", "do"] as $w) { $t->insert($w); }
echo json_encode($t->complete("ca")) . "\n"; // ["cat","car"]
echo var_export($t->startsWith("do"), true) . "\n"; // true
echo var_export($t->startsWith("cow"), true) . "\n"; // falseJavaScript
class TrieNode {
constructor() {
this.kids = {}; // letter -> TrieNode
this.end = false; // does a word finish here?
}
}
class Trie {
constructor() { this.root = new TrieNode(); }
insert(word) {
let node = this.root;
for (const ch of word) {
if (!node.kids[ch]) {
node.kids[ch] = new TrieNode(); // grow a new branch
}
node = node.kids[ch];
}
node.end = true; // a word ends here
}
// Walk down the prefix; return the node, or null if it does not exist.
find(prefix) {
let node = this.root;
for (const ch of prefix) {
node = node.kids[ch];
if (!node) { return null; }
}
return node;
}
startsWith(prefix) {
return this.find(prefix) !== null;
}
// Autocomplete: all words below the prefix node.
complete(prefix) {
const node = this.find(prefix);
const out = [];
if (node) { this.collect(node, prefix, out); }
return out;
}
collect(node, path, out) {
if (node.end) { out.push(path); }
for (const ch in node.kids) {
this.collect(node.kids[ch], path + ch, out);
}
}
}
const t = new Trie();
for (const w of ['cat', 'car', 'dog', 'do']) { t.insert(w); }
console.log(JSON.stringify(t.complete('ca'))); // ["cat","car"]
console.log(t.startsWith('do')); // true
console.log(t.startsWith('cow')); // falseJava
import java.util.*;
public class Main {
static class TrieNode {
Map<Character, TrieNode> kids = new LinkedHashMap<>(); // letter -> TrieNode
boolean end = false; // does a word finish here?
}
static class Trie {
private final TrieNode root = new TrieNode();
void insert(String word) {
TrieNode node = root;
for (char ch : word.toCharArray()) {
if (!node.kids.containsKey(ch)) {
node.kids.put(ch, new TrieNode()); // grow a new branch
}
node = node.kids.get(ch);
}
node.end = true; // a word ends here
}
// Walk down the prefix; return the node, or null if it does not exist.
private TrieNode find(String prefix) {
TrieNode node = root;
for (char ch : prefix.toCharArray()) {
node = node.kids.get(ch);
if (node == null) { return null; }
}
return node;
}
boolean startsWith(String prefix) {
return find(prefix) != null;
}
// Autocomplete: all words below the prefix node.
List<String> complete(String prefix) {
TrieNode node = find(prefix);
List<String> out = new ArrayList<>();
if (node != null) { collect(node, prefix, out); }
return out;
}
private void collect(TrieNode node, String path, List<String> out) {
if (node.end) { out.add(path); }
for (Map.Entry<Character, TrieNode> e : node.kids.entrySet()) {
collect(e.getValue(), path + e.getKey(), out);
}
}
}
public static void main(String[] args) {
Trie t = new Trie();
for (String w : new String[]{"cat", "car", "dog", "do"}) { t.insert(w); }
System.out.println(t.complete("ca")); // [cat, car]
System.out.println(t.startsWith("do")); // true
System.out.println(t.startsWith("cow")); // false
}
}Go
package main
import "fmt"
type TrieNode struct {
kids map[rune]*TrieNode // letter -> TrieNode
order []rune // letters in the order they were added (Go maps have no order)
end bool // does a word finish here?
}
func newNode() *TrieNode {
return &TrieNode{kids: map[rune]*TrieNode{}}
}
type Trie struct {
root *TrieNode
}
func NewTrie() *Trie {
return &Trie{root: newNode()}
}
func (t *Trie) Insert(word string) {
node := t.root
for _, ch := range word {
if _, ok := node.kids[ch]; !ok {
node.kids[ch] = newNode() // grow a new branch
node.order = append(node.order, ch)
}
node = node.kids[ch]
}
node.end = true // a word ends here
}
// find walks down the prefix; it returns nil if the prefix does not exist.
func (t *Trie) find(prefix string) *TrieNode {
node := t.root
for _, ch := range prefix {
node = node.kids[ch]
if node == nil {
return nil
}
}
return node
}
func (t *Trie) StartsWith(prefix string) bool {
return t.find(prefix) != nil
}
// Complete is autocomplete: all words below the prefix node.
func (t *Trie) Complete(prefix string) []string {
var out []string
if node := t.find(prefix); node != nil {
collect(node, prefix, &out)
}
return out
}
func collect(node *TrieNode, path string, out *[]string) {
if node.end {
*out = append(*out, path)
}
for _, ch := range node.order {
collect(node.kids[ch], path+string(ch), out)
}
}
func main() {
t := NewTrie()
for _, w := range []string{"cat", "car", "dog", "do"} {
t.Insert(w)
}
fmt.Println(t.Complete("ca")) // [cat car]
fmt.Println(t.StartsWith("do")) // true
fmt.Println(t.StartsWith("cow")) // false
}Time: O(L) per insert or lookup (L = word length) · Extra space: O(total letters). The work depends on the length of the word, not on how many words are stored. Shared prefixes are stored only once.
Watch out for
- Forgetting the "word ends here" flag. Without it, "do" cannot be told apart from the beginning of "dog".
- Assuming a prefix is a word.
startsWith("ca")being true does not mean "ca" is stored as a word. - Storing a full string in every node instead of a single letter, which wastes memory and loses the sharing.
Quick check
- Why do CAT and CAR share nodes?
- They are anagrams
- They begin with the same letters C and A
- They have the same length
- How many steps does it take to check whether any word starts with "ca"?
- 2, one per letter of the prefix
- As many as the words stored
- 1
- Why mark a node as "end of word"?
- To delete it later
- To save memory
- To tell "do" (a word) from a mere prefix of "dog"