Search
Beginner · 7 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Searching a trie means walking the letters of a word and then checking the "word ends here" flag. It answers "is this exact word in my list?" in a time that depends only on the word length, not on how many words you stored.
Practical use cases
- Web app: Banned and common password check. On the sign-up form, the server must reject passwords like "password123" from a list of 100,000 leaked ones. Walking the typed password through a trie gives a yes or no in a few steps, so the check can run on every form submit without slowing registration.
- Web app: Is this username available?. While someone types a username on a registration page, the app says "taken" or "available" almost instantly. A trie of existing names finds an exact match by following the letters, and the flag at the end tells the difference between a real username and just the beginning of a longer one.
- System: Spell checkers and word games. A spell checker asks whether a typed word is in the dictionary, and a word game asks whether a tile combination is a real word. Both walk the letters and check the flag, which is much quicker than comparing with every word.
The story: Is This Name on the Board?
Raju's chai stall had a tiny regulars' board: customers who got one free chai after ten cups. A schoolboy walked up and said, "Am I on it? My name is Aman."
Raju did not read the whole board. He pointed a finger at the first lane: A. Then M. Then A. Then N. Each lane existed! "Found... wait." The last box had no green flag. "Aman" was only the beginning of Amanpreet, who was a regular. So the answer to "is Aman on the board?" was no.
A second boy asked about "Zubin". Raju looked for a Z lane at the start. There was none. Answer in one glance: no.
There are exactly two ways a trie search says no: a letter has no lane to follow, or the letters are over but you stand on a box with no green flag. Only "all letters followed AND flag is green" says yes.
How to spot this problem, and where you need it
You must decide again and again whether an exact word or code is in a large set, and looping over the whole set each time makes the feature sluggish.
Signs you need it
- The feature is a yes/no membership check against a big list: banned words, reserved names, valid codes.
- You call in_array() or a SQL query on a big list every time a user types or submits.
- You need to tell "this is a complete word" apart from "this is only the beginning of a word".
- The problem asks to "search a word in a dictionary" built from many strings.
Where to use it in a project
- Registration and password-change forms that check names and passwords against blocklists.
- Validation of promo codes, tags or keywords held in memory.
The solution
Start at the root and follow the child for each letter of the word. If any letter has no child, the word is not there, so stop and answer no. If you manage to walk all letters, look at the node you are standing on: if it has the end-of-word flag, answer yes, otherwise it was only a prefix of something longer, so answer no.
Payoff: Before: comparing against 100,000 stored words per check. After: about 10 steps, regardless of list size.
Explain it like I am 8
Walk along the lanes, one letter at a time. If a lane is missing, you are lost: the word is not here. If you walk the whole word, look at the box you stand on: is there a green flag? Green means yes. No flag means the word is only the start of a longer one.
How it works, step by step
- Start at the root.
- For each letter, look for that child. If it is missing, stop and answer false.
- Otherwise move to the child and read the next letter.
- When the letters are finished, return the node's end flag.
- Searching never changes the trie, and its cost depends only on the word length.
The code in four languages
PHP
<?php
class TrieNode {
public array $kids = [];
public bool $end = false;
}
class Trie {
private TrieNode $root;
public function __construct() { $this->root = new TrieNode(); }
public function insert(string $word): void {
$node = $this->root;
foreach (str_split($word) as $ch) {
$node->kids[$ch] ??= new TrieNode();
$node = $node->kids[$ch];
}
$node->end = true;
}
// true only if the exact word was inserted
public function search(string $word): bool {
$node = $this->root;
foreach (str_split($word) as $ch) {
if (!isset($node->kids[$ch])) { return false; } // lane missing
$node = $node->kids[$ch];
}
return $node->end; // flag decides
}
}
$t = new Trie();
foreach (['cat', 'car', 'cub', 'do', 'dog'] as $w) { $t->insert($w); }
foreach (['car', 'ca', 'cow', 'do', 'd'] as $q) {
echo $q . ': ' . ($t->search($q) ? 'yes' : 'no') . PHP_EOL;
}JavaScript
class TrieNode {
constructor() { this.kids = {}; this.end = false; }
}
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();
node = node.kids[ch];
}
node.end = true;
}
// true only if the exact word was inserted
search(word) {
let node = this.root;
for (const ch of word) {
if (!node.kids[ch]) return false; // lane missing
node = node.kids[ch];
}
return node.end; // flag decides
}
}
const t = new Trie();
for (const w of ['cat', 'car', 'cub', 'do', 'dog']) t.insert(w);
for (const q of ['car', 'ca', 'cow', 'do', 'd']) {
console.log(q + ': ' + (t.search(q) ? 'yes' : 'no'));
}Java
import java.util.*;
public class Main {
static class TrieNode {
Map<Character, TrieNode> kids = new HashMap<>();
boolean end = false;
}
static class Trie {
private final TrieNode root = new TrieNode();
void insert(String word) {
TrieNode node = root;
for (char ch : word.toCharArray()) {
node.kids.putIfAbsent(ch, new TrieNode());
node = node.kids.get(ch);
}
node.end = true;
}
// true only if the exact word was inserted
boolean search(String word) {
TrieNode node = root;
for (char ch : word.toCharArray()) {
if (!node.kids.containsKey(ch)) return false; // lane missing
node = node.kids.get(ch);
}
return node.end; // flag decides
}
}
public static void main(String[] args) {
Trie t = new Trie();
for (String w : new String[]{"cat", "car", "cub", "do", "dog"}) t.insert(w);
for (String q : new String[]{"car", "ca", "cow", "do", "d"}) {
System.out.println(q + ": " + (t.search(q) ? "yes" : "no"));
}
}
}Go
package main
import "fmt"
type TrieNode struct {
kids map[rune]*TrieNode
end bool
}
func newTrieNode() *TrieNode { return &TrieNode{kids: map[rune]*TrieNode{}} }
type Trie struct {
root *TrieNode
}
func NewTrie() *Trie { return &Trie{root: newTrieNode()} }
func (t *Trie) Insert(word string) {
node := t.root
for _, ch := range word {
if node.kids[ch] == nil {
node.kids[ch] = newTrieNode()
}
node = node.kids[ch]
}
node.end = true
}
// Search is true only if the exact word was inserted.
func (t *Trie) Search(word string) bool {
node := t.root
for _, ch := range word {
if node.kids[ch] == nil {
return false // lane missing
}
node = node.kids[ch]
}
return node.end // flag decides
}
func main() {
t := NewTrie()
for _, w := range []string{"cat", "car", "cub", "do", "dog"} {
t.Insert(w)
}
for _, q := range []string{"car", "ca", "cow", "do", "d"} {
answer := "no"
if t.Search(q) {
answer = "yes"
}
fmt.Printf("%s: %s\n", q, answer)
}
}Time: O(L) · Extra space: O(1). You take one step per letter of the word you are searching, however large the dictionary is.
Watch out for
- Returning true after walking all letters without checking the end flag (so every prefix looks like a word).
- Returning the flag of a node that does not exist because the loop ignored a missing child.
- Searching for the empty string and expecting false/true without deciding the rule up front.
Quick check
- The trie holds only "cat". What does search("ca") return?
- true
- false
- Which search returns false the fastest?
- A word whose first letter is missing under the root
- A word that is stored
- A word with 10 letters that exists
- The cost of a search depends on...
- the number of words stored
- the length of the searched word
- the alphabet order