Trie
Intermediate · 10 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
A trie stores many words so that words with the same beginning share the same path. In string algorithms it is the base of fast prefix lookups and of more advanced tools like multi-keyword matching.
Practical use cases
- Web app: Search suggestions as you type. A shop or travel site shows suggestions as soon as the user types two letters. With the names in a trie, the app walks the typed letters and lists what is underneath, which takes the same short time for 10,000 or 10 million entries.
- Web app: Contact and phone lookup. A web dialler finds contacts as digits or letters are typed. Instead of filtering the entire phone book on each key, it follows one path in the trie, so the list narrows without lag. Typing feels smooth on a phone, and the server never has to run a search for every letter.
- System: Spell checkers and routing tables. Spell checkers test whether a typed beginning can still become a word, and routers match address prefixes. Both depend on the shared-start layout of a trie. These tools respond in a few milliseconds because they never look at words that do not share the typed start.
The story: Grandpa's Phone Book Tree
Grandpa Bhaskar never trusted his new smartphone, so Mira built him a game: she typed a few letters and the phone suggested names. "How does it know so fast?" he wondered. His old paper phone book was sorted, but to find everyone starting with "Ca" he still had to flip pages and squint.
Mira drew a tree on the back of a calendar. At the top, a dot. From it, one branch per first letter. Under the "C" branch, branches for the next letter, and so on. Names that start the same share the same branches: Car, Card, Care and Cat all walk down C-A together and split later. To spell a name you simply walk from the top.
On every circle she wrote a small number: how many names pass through it. To ask "how many names start with CAR?" Grandpa walked three steps and read the number. To suggest names he walked to "CA" and read everything below. He did not care if the phone book had ten names or ten lakh: the work depended only on the length of what he typed. This letter tree is a trie (say "try").
How to spot this problem, and where you need it
You keep a big set of strings and constantly ask what starts with some letters, and scanning every string each time is too slow.
Signs you need it
- Features like autocomplete, suggestions, and prefix filters sit on top of a big list.
- Your search uses repeated LIKE 'x%' queries or loops with startsWith.
- Many strings share beginnings, such as URLs, paths or product names.
- The problem asks for "words with prefix" or "dictionary operations".
Where to use it in a project
- Search suggestion boxes and typeahead components in apps.
- Phone, email and address lookups, and validation against reserved prefixes.
The solution
Create a tree with one branch per next letter. Insert each word by walking and extending its letters and marking its end. To use it, walk the letters typed; the node you reach represents the prefix, and everything under it is a match. Cost depends on word length rather than on how many words are stored.
Payoff: Before: scanning every name on each keystroke. After: a few steps per keystroke, so suggestions feel instant.
Explain it like I am 8
Think of a family tree for words. Words that begin the same way share the same trunk and only split into branches where they become different. To check a word, walk along the branches letter by letter: if the path breaks, the word is not there.
How it works, step by step
- Make a root node with no letter. Every node holds a map from a letter to a child node, a counter, and a flag "a word ends here".
- Insert a word: start at the root; for each letter go to that child (create it if missing) and add one to its counter.
- At the last letter set the "word ends here" flag.
- Search or prefix count: walk the letters; if a child is missing, answer no (or 0). Otherwise read the end flag or the counter.
- Autocomplete: walk to the prefix node, then depth-first search below it collecting every node whose end flag is set.
The code in four languages
PHP
<?php
// A trie node: children by letter, how many words pass through, and an end flag.
class TrieNode {
public array $kids = [];
public int $pass = 0;
public bool $end = false;
}
class Trie {
private TrieNode $root;
public function __construct() { $this->root = new TrieNode(); }
public function insert(string $w): void {
$cur = $this->root;
for ($i = 0; $i < strlen($w); $i++) {
$c = $w[$i];
if (!isset($cur->kids[$c])) $cur->kids[$c] = new TrieNode();
$cur = $cur->kids[$c];
$cur->pass++; // one more word goes through here
}
$cur->end = true;
}
private function walk(string $p): ?TrieNode {
$cur = $this->root;
for ($i = 0; $i < strlen($p); $i++) {
if (!isset($cur->kids[$p[$i]])) return null; // path breaks
$cur = $cur->kids[$p[$i]];
}
return $cur;
}
public function has(string $w): bool { $n = $this->walk($w); return $n !== null && $n->end; }
public function countPrefix(string $p): int { $n = $this->walk($p); return $n ? $n->pass : 0; }
public function complete(string $p): array {
$n = $this->walk($p); $out = [];
if ($n) $this->collect($n, $p, $out);
return $out;
}
private function collect(TrieNode $n, string $acc, array &$out): void {
if ($n->end) $out[] = $acc;
ksort($n->kids); // alphabetical order
foreach ($n->kids as $c => $child) $this->collect($child, $acc . $c, $out);
}
}
$t = new Trie();
foreach (["car", "card", "care", "cat", "dog"] as $w) $t->insert($w);
echo $t->countPrefix("car"), " ", $t->countPrefix("cap"), " ", var_export($t->has("ca"), true), "\n"; // 3 0 false
echo implode(",", $t->complete("ca")), "\n"; // car,card,care,catJavaScript
// A trie node: children by letter, how many words pass through, and an end flag.
class TrieNode {
constructor() { this.kids = new Map(); this.pass = 0; this.end = false; }
}
class Trie {
constructor() { this.root = new TrieNode(); }
insert(w) {
let cur = this.root;
for (const c of w) {
if (!cur.kids.has(c)) cur.kids.set(c, new TrieNode());
cur = cur.kids.get(c);
cur.pass++; // one more word goes through here
}
cur.end = true;
}
walk(p) {
let cur = this.root;
for (const c of p) {
if (!cur.kids.has(c)) return null; // path breaks
cur = cur.kids.get(c);
}
return cur;
}
has(w) { const n = this.walk(w); return n !== null && n.end; }
countPrefix(p) { const n = this.walk(p); return n ? n.pass : 0; }
complete(p) {
const n = this.walk(p), out = [];
if (n) this.collect(n, p, out);
return out;
}
collect(n, acc, out) {
if (n.end) out.push(acc);
for (const c of [...n.kids.keys()].sort()) this.collect(n.kids.get(c), acc + c, out);
}
}
const t = new Trie();
for (const w of ["car", "card", "care", "cat", "dog"]) t.insert(w);
console.log(t.countPrefix("car"), t.countPrefix("cap"), t.has("ca")); // 3 0 false
console.log(t.complete("ca").join(",")); // car,card,care,catJava
import java.util.*;
public class Main {
// A trie node: children by letter, how many words pass through, and an end flag.
static class TrieNode {
Map<Character, TrieNode> kids = new TreeMap<>(); // TreeMap keeps letters alphabetical
int pass = 0;
boolean end = false;
}
static class Trie {
TrieNode root = new TrieNode();
void insert(String w) {
TrieNode cur = root;
for (char c : w.toCharArray()) {
cur.kids.putIfAbsent(c, new TrieNode());
cur = cur.kids.get(c);
cur.pass++; // one more word goes through here
}
cur.end = true;
}
TrieNode walk(String p) {
TrieNode cur = root;
for (char c : p.toCharArray()) {
if (!cur.kids.containsKey(c)) return null; // path breaks
cur = cur.kids.get(c);
}
return cur;
}
boolean has(String w) { TrieNode n = walk(w); return n != null && n.end; }
int countPrefix(String p) { TrieNode n = walk(p); return n != null ? n.pass : 0; }
List<String> complete(String p) {
TrieNode n = walk(p);
List<String> out = new ArrayList<>();
if (n != null) collect(n, p, out);
return out;
}
void collect(TrieNode n, String acc, List<String> out) {
if (n.end) out.add(acc);
for (var e : n.kids.entrySet()) collect(e.getValue(), acc + e.getKey(), out);
}
}
public static void main(String[] args) {
Trie t = new Trie();
for (String w : List.of("car", "card", "care", "cat", "dog")) t.insert(w);
System.out.println(t.countPrefix("car") + " " + t.countPrefix("cap") + " " + t.has("ca")); // 3 0 false
System.out.println(String.join(",", t.complete("ca"))); // car,card,care,cat
}
}Go
package main
import (
"fmt"
"sort"
"strings"
)
// TrieNode: children by letter, how many words pass through, and an end flag.
type TrieNode struct {
kids map[rune]*TrieNode
pass int
end bool
}
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(w string) {
cur := t.root
for _, c := range w {
if _, ok := cur.kids[c]; !ok {
cur.kids[c] = newNode()
}
cur = cur.kids[c]
cur.pass++ // one more word goes through here
}
cur.end = true
}
func (t *Trie) walk(p string) *TrieNode {
cur := t.root
for _, c := range p {
next, ok := cur.kids[c]
if !ok {
return nil // path breaks
}
cur = next
}
return cur
}
func (t *Trie) Has(w string) bool {
n := t.walk(w)
return n != nil && n.end
}
func (t *Trie) CountPrefix(p string) int {
if n := t.walk(p); n != nil {
return n.pass
}
return 0
}
func (t *Trie) Complete(p string) []string {
var out []string
if n := t.walk(p); n != nil {
collect(n, p, &out)
}
return out
}
func collect(n *TrieNode, acc string, out *[]string) {
if n.end {
*out = append(*out, acc)
}
letters := make([]rune, 0, len(n.kids))
for c := range n.kids {
letters = append(letters, c)
}
sort.Slice(letters, func(i, j int) bool { return letters[i] < letters[j] }) // alphabetical order
for _, c := range letters {
collect(n.kids[c], acc+string(c), out)
}
}
func main() {
t := NewTrie()
for _, w := range []string{"car", "card", "care", "cat", "dog"} {
t.Insert(w)
}
fmt.Println(t.CountPrefix("car"), t.CountPrefix("cap"), t.Has("ca")) // 3 0 false
fmt.Println(strings.Join(t.Complete("ca"), ",")) // car,card,care,cat
}Time: O(L) per insert or query · Extra space: O(total letters). L is the length of the word you handle. Work never depends on how many words are stored.
Watch out for
- Mixing up "this path exists" with "a word ends here". "ca" is a path but not a stored word.
- Forgetting to bump the pass counter while inserting, which breaks prefix counts.
- Using a huge fixed array per node for a big alphabet; a map of only existing children saves a lot of memory.
Quick check
- How long does it take to count words with prefix "car" in a trie of a million words?
- About a million steps
- About 3 steps (length of the prefix)
- It needs sorting first
- Why does a trie save space for words like car, card, care?
- It compresses letters into numbers
- Shared beginnings are stored once
- It deletes duplicates later
- The path "ca" exists in our trie but has() says false. Why?
- A bug
- No word ends exactly at "ca"
- Tries cannot hold short words