Prefix search
Beginner · 7 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Prefix search asks only whether any stored word begins with the letters given. Since a path in a trie exists only if some stored word uses it, simply being able to walk the typed letters is already the answer, with no end-of-word flag needed.
Practical use cases
- Web app: Catalogue filter as you type. On a category page of a store, a user types "wire" and the page should list wireless headphones, wireless chargers and wired mice. Walking the letters W, I, R, E in a trie of product names instantly tells you the matching group, so the page stops scanning thousands of rows on every key.
- Web app: Contact finder with "no match" message. In a phone-contact web page, the moment the typed letters have no matching road in the trie, the app can show "no contact starts with this" immediately. It does not need to read the whole contact list to know the answer is empty. A clear message beats a blank dropdown, because the user knows at once to fix a typo.
- System: Word-game solvers. A Boggle-style solver extends a path of letters across a grid. If no word starts with the current letters, it abandons that path at once, which cuts the work from millions of paths to a few thousand. The whole speed-up comes from one simple question asked at every step: can any word still start this way?
The story: Mrs. Sharma's Roll Call
Mrs. Sharma took the roll call every morning from a long sheet of 300 student names. One day the principal peeped in and asked, "Is there any student whose name starts with Pri?" Mrs. Sharma ran a finger down the sheet. Priya? Pritam? She was not even sure how many Pris she had.
Mira had built a lane-of-letters board for the class (a trie!) as a science project. She said, "Ma'am, give me three seconds." She walked P, R, I along the lanes. All three existed. "Yes! And everything below this box starts with Pri: two students."
Notice what Mira did not do. She did not check for a green flag at I; "Pri" is not a name. Having arrived at the box at all was already the proof that some name begins that way.
This is prefix search (often called startsWith). It is search without the flag check: if you can walk every letter of the prefix, the answer is yes. As a bonus, if each box remembers how many words pass through it, even "how many?" becomes instant.
How to spot this problem, and where you need it
You need to know whether anything starts with a given beginning, often many times in a row, and re-checking the whole list each time wastes effort.
Signs you need it
- The question is "does any word start with...?" rather than "is this exact word present?".
- You are growing a partial word letter by letter and need to stop as soon as it cannot lead anywhere.
- Your search box code uses LIKE 'abc%' or startsWith inside a loop over everything.
- The same prefix questions repeat, with one more letter each time.
Where to use it in a project
- Typeahead boxes that must decide quickly whether there are any suggestions at all.
- Backtracking code, such as a word-grid solver, that prunes dead ends early.
The solution
Walk the trie along the letters of the prefix. If you fall off the road at any letter, no word starts that way, so answer no immediately. If you reach the end of the prefix, answer yes, because roads only exist for words that were inserted. You never need to look at the end flag for this question.
Payoff: Before: scanning every word for each new letter typed. After: one step per letter, and dead ends are spotted immediately.
Explain it like I am 8
Walk the letters of the beginning only. If the road exists, then some word goes that way, because roads are only built for real words. You do not even need to find a flag.
How it works, step by step
- Start at the root with the prefix you are asked about.
- Follow one child per letter. If a lane is missing, answer false.
- If you finish all letters of the prefix, answer true: some word passes through here.
- The box you stand on is the root of a small sub-trie that holds every word with that prefix.
- Optional: store a counter on each node (how many words pass through) to answer "how many words start with this?" in the same walk.
The code in four languages
PHP
<?php
class TrieNode {
public array $kids = [];
public bool $end = false;
public int $pass = 0; // how many words pass through this box
}
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->pass++; // one more word goes through
}
$node->end = true;
}
private function walk(string $s): ?TrieNode {
$node = $this->root;
foreach (str_split($s) as $ch) {
if (!isset($node->kids[$ch])) { return null; }
$node = $node->kids[$ch];
}
return $node;
}
public function startsWith(string $prefix): bool { return $this->walk($prefix) !== null; }
public function countWithPrefix(string $prefix): int {
$n = $this->walk($prefix);
return $n === null ? 0 : $n->pass;
}
}
$t = new Trie();
foreach (['cat', 'car', 'cub', 'do', 'dog'] as $w) { $t->insert($w); }
foreach (['ca', 'cu', 'cx', 'do', 'dogs'] as $p) {
echo $p . ': ' . ($t->startsWith($p) ? 'yes' : 'no') . ', count ' . $t->countWithPrefix($p) . PHP_EOL;
}JavaScript
class TrieNode {
constructor() {
this.kids = {};
this.end = false;
this.pass = 0; // how many words pass through this box
}
}
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.pass++; // one more word goes through
}
node.end = true;
}
walk(s) {
let node = this.root;
for (const ch of s) {
if (!node.kids[ch]) return null;
node = node.kids[ch];
}
return node;
}
startsWith(prefix) { return this.walk(prefix) !== null; }
countWithPrefix(prefix) {
const n = this.walk(prefix);
return n === null ? 0 : n.pass;
}
}
const t = new Trie();
for (const w of ['cat', 'car', 'cub', 'do', 'dog']) t.insert(w);
for (const p of ['ca', 'cu', 'cx', 'do', 'dogs']) {
console.log(p + ': ' + (t.startsWith(p) ? 'yes' : 'no') + ', count ' + t.countWithPrefix(p));
}Java
import java.util.*;
public class Main {
static class TrieNode {
Map<Character, TrieNode> kids = new HashMap<>();
boolean end = false;
int pass = 0; // how many words pass through this box
}
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.pass++; // one more word goes through
}
node.end = true;
}
private TrieNode walk(String s) {
TrieNode node = root;
for (char ch : s.toCharArray()) {
if (!node.kids.containsKey(ch)) return null;
node = node.kids.get(ch);
}
return node;
}
boolean startsWith(String prefix) { return walk(prefix) != null; }
int countWithPrefix(String prefix) {
TrieNode n = walk(prefix);
return n == null ? 0 : n.pass;
}
}
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 p : new String[]{"ca", "cu", "cx", "do", "dogs"}) {
System.out.println(p + ": " + (t.startsWith(p) ? "yes" : "no") + ", count " + t.countWithPrefix(p));
}
}
}Go
package main
import "fmt"
type TrieNode struct {
kids map[rune]*TrieNode
end bool
pass int // how many words pass through this box
}
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.pass++ // one more word goes through
}
node.end = true
}
// walk follows s from the root and returns the box it ends on, or nil.
func (t *Trie) walk(s string) *TrieNode {
node := t.root
for _, ch := range s {
if node.kids[ch] == nil {
return nil
}
node = node.kids[ch]
}
return node
}
func (t *Trie) StartsWith(prefix string) bool { return t.walk(prefix) != nil }
func (t *Trie) CountWithPrefix(prefix string) int {
n := t.walk(prefix)
if n == nil {
return 0
}
return n.pass
}
func main() {
t := NewTrie()
for _, w := range []string{"cat", "car", "cub", "do", "dog"} {
t.Insert(w)
}
for _, p := range []string{"ca", "cu", "cx", "do", "dogs"} {
answer := "no"
if t.StartsWith(p) {
answer = "yes"
}
fmt.Printf("%s: %s, count %d\n", p, answer, t.CountWithPrefix(p))
}
}Time: O(P) · Extra space: O(1). P is the length of the prefix. The answer needs one step per prefix letter, not a scan of all words.
Watch out for
- Requiring the end flag for a prefix check; a prefix does not have to be a word.
- Forgetting to bump the pass counter when you insert a word that shares only part of the path.
- Counting a prefix longer than any stored word (like "dogs") as present: the walk must really succeed.
Quick check
- The trie holds "dog". Does startsWith("do") return true?
- No, "do" is not stored
- Yes, the path d-o exists
- Only if "do" has an end flag
- What is the difference between search and startsWith?
- startsWith also checks the end flag
- search checks the end flag, startsWith does not
- No difference
- What does a "pass" counter on each node make possible?
- Instantly counting words with a given prefix
- Sorting the words
- Deleting words faster only