AlgoTales · Roadmap

Trie structure

Beginner · 7 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

A trie is a tree where each step down is one letter, so words that start the same share the same path. It lets you answer questions about the beginning of words very quickly, which is why it sits behind many search boxes and suggestion lists.

Practical use cases

  • Web app: Search box suggestions in a shop. As a shopper types "sam" in a product search, the page must show "samsung", "samosa maker" and "sambar masala" at once. A trie of product names has a path S, A, M and everything below it is a suggestion. The lookup time depends on the letters typed, not on whether the catalogue has 1,000 or 1,000,000 products.
  • Web app: Contacts list on a dialler page. A CRM page lets a sales rep type the first letters of a customer name and instantly narrows the list. Instead of scanning every contact with a LIKE query on each keystroke, a trie built once in memory answers from the typed letters alone, so the list updates smoothly with no database round trip for each key press.
  • System: IP routing and spell checkers. Routers match the beginning of an address against rules, and spell checkers test word beginnings. Both use trie-like structures because shared beginnings are stored only once, saving space and time. This is also why the same structure shows up in phone keyboards, which must suggest words instantly on very small hardware.

The story: The Lane of Letters

In Mira's mohalla there was a very old post office, and old Grandpa Bhaskar was its postmaster. Letters were sorted into a huge wall of pigeonholes, one hole per name: "Chandu", "Charu", "Chitra", "Dilip", "Dinesh". Every month the wall got fuller, and every month he repeated the same chore: writing "Ch" on a hundred little labels.

One monsoon evening Mira watched him paint labels and said, "Dada, why write C-H again and again? Paint it once on the lane sign, then split the lane." Grandpa laughed. "A lane for C. Inside it, a lane for H. Then the lane splits: A for Charu, I for Chitra, A-N for Chandu..." He walked to the board and drew it: one road, forking letter by letter.

Kabir tested it: "Is there anybody whose name starts with Chi?" Mira simply walked down C, H, I and found a house. No reading of every pigeonhole! "But how do I know that Chi itself is not a name?" asked Kabir. Grandpa stuck a small green flag on the houses where a name really ends.

That lane of letters has a name in computer science: a trie (say "try", from retrieval), also called a prefix tree. Words that begin the same way share the same path, and a flag marks where a real word ends.

How to spot this problem, and where you need it

You have a big list of words, names or codes and keep asking things about how they begin, and scanning the entire list for each question is making the feature slow.

Signs you need it

  • The feature is search-as-you-type, suggestions, or "starts with" filtering over thousands of strings.
  • Your code loops through every string checking strpos or startsWith for each keystroke.
  • Many of your strings share the same beginnings, such as product brands, city names or file paths.
  • The problem says "words with a given prefix", "dictionary" or "wildcard at the end".

Where to use it in a project

  • Autocomplete for search boxes, address fields, tag inputs and mention lists.
  • Validating or classifying codes by their leading digits, like phone prefixes or IP ranges.

The solution

Build a tree where every node represents one letter and its children are the possible next letters. Insert each word by following and creating its letters, and mark the final node as "a word ends here". To ask about a beginning, just walk the typed letters; whatever is below that node is exactly the set of matching words. Shared beginnings are stored once.

Payoff: Before: scanning 500,000 names on every keystroke. After: walking 3 to 10 letters, so suggestions show up instantly.

Explain it like I am 8

Imagine a road that splits at every letter. To visit "cat" you walk C, then A, then T. To visit "car" you walk the same road C, A and only turn off at the last step. A little green flag says "a word ends here".

How it works, step by step

  1. Start with an empty root node. It has no letter; it only holds a list of children.
  2. Every node keeps its children: a small map from a letter to the next node ({ c: node, d: node }).
  3. Every node also keeps an end flag: true if a stored word finishes exactly here.
  4. A word is the path from the root: read its letters, follow one child per letter.
  5. Words with the same beginning share the same first boxes, so common prefixes are stored only once.

The code in four languages

PHP

<?php
// A trie node = a map of children + an "a word ends here" flag.
function newNode(): array { return ['kids' => [], 'end' => false]; }

$words = ['cat', 'car', 'cub', 'do', 'dog'];
$root = newNode();
foreach ($words as $w) {
    $node = &$root;                       // walk with a reference, starting at the root
    foreach (str_split($w) as $ch) {
        if (!isset($node['kids'][$ch])) { // missing letter: build the box
            $node['kids'][$ch] = newNode();
        }
        $node = &$node['kids'][$ch];      // step down one letter
    }
    $node['end'] = true;                  // plant the green flag
    unset($node);
}

function countBoxes(array $n): int {
    $c = 0;
    foreach ($n['kids'] as $kid) { $c += 1 + countBoxes($kid); }
    return $c;
}
function show(array $n, string $pad = ''): void {
    foreach ($n['kids'] as $ch => $kid) {
        echo $pad . $ch . ($kid['end'] ? ' *' : '') . PHP_EOL;
        show($kid, $pad . '  ');
    }
}
show($root);
echo 'Boxes used: ' . countBoxes($root) . PHP_EOL;   // 9, not 14

JavaScript

// A trie node = a map of children + an "a word ends here" flag.
const newNode = () => ({ kids: {}, end: false });

const words = ['cat', 'car', 'cub', 'do', 'dog'];
const root = newNode();
for (const w of words) {
  let node = root;                    // walk starting at the root
  for (const ch of w) {
    if (!node.kids[ch]) {             // missing letter: build the box
      node.kids[ch] = newNode();
    }
    node = node.kids[ch];             // step down one letter
  }
  node.end = true;                    // plant the green flag
}

function countBoxes(n) {
  let c = 0;
  for (const ch in n.kids) c += 1 + countBoxes(n.kids[ch]);
  return c;
}
function show(n, pad) {
  for (const ch in n.kids) {
    console.log(pad + ch + (n.kids[ch].end ? ' *' : ''));
    show(n.kids[ch], pad + '  ');
  }
}
show(root, '');
console.log('Boxes used: ' + countBoxes(root));   // 9, not 14

Java

import java.util.*;

public class Main {
    // A trie node = a map of children + an "a word ends here" flag.
    static class Node {
        Map<Character, Node> kids = new LinkedHashMap<>();   // keeps insertion order for printing
        boolean end = false;
    }

    static int countBoxes(Node n) {
        int c = 0;
        for (Node kid : n.kids.values()) c += 1 + countBoxes(kid);
        return c;
    }

    static void show(Node n, String pad) {
        for (var entry : n.kids.entrySet()) {
            Node kid = entry.getValue();
            System.out.println(pad + entry.getKey() + (kid.end ? " *" : ""));
            show(kid, pad + "  ");
        }
    }

    public static void main(String[] args) {
        String[] words = {"cat", "car", "cub", "do", "dog"};
        Node root = new Node();
        for (String w : words) {
            Node node = root;                       // walk starting at the root
            for (char ch : w.toCharArray()) {
                if (!node.kids.containsKey(ch)) {   // missing letter: build the box
                    node.kids.put(ch, new Node());
                }
                node = node.kids.get(ch);           // step down one letter
            }
            node.end = true;                        // plant the green flag
        }

        show(root, "");
        System.out.println("Boxes used: " + countBoxes(root));   // 9, not 14
    }
}

Go

package main

import "fmt"

// A trie node = a map of children + an "a word ends here" flag.
type node struct {
	kids  map[rune]*node
	order []rune // letters in the order they were added, so printing is stable
	end   bool
}

func newNode() *node { return &node{kids: map[rune]*node{}} }

func countBoxes(n *node) int {
	c := 0
	for _, kid := range n.kids {
		c += 1 + countBoxes(kid)
	}
	return c
}

func show(n *node, pad string) {
	for _, ch := range n.order {
		kid := n.kids[ch]
		mark := ""
		if kid.end {
			mark = " *"
		}
		fmt.Println(pad + string(ch) + mark)
		show(kid, pad+"  ")
	}
}

func main() {
	words := []string{"cat", "car", "cub", "do", "dog"}
	root := newNode()
	for _, w := range words {
		n := root // walk starting at the root
		for _, ch := range w {
			if n.kids[ch] == nil { // missing letter: build the box
				n.kids[ch] = newNode()
				n.order = append(n.order, ch)
			}
			n = n.kids[ch] // step down one letter
		}
		n.end = true // plant the green flag
	}

	show(root, "")
	fmt.Println("Boxes used:", countBoxes(root)) // 9, not 14
}

Time: O(total letters) · Extra space: O(total letters). Building costs one step per letter; shared prefixes mean the real memory is often much smaller than the sum of the words.

Watch out for

  • Forgetting the end flag: then "ca" looks like a stored word just because "cat" passes through it.
  • Thinking the root holds a letter. It is only the starting point; letters live on the boxes below it.
  • Assuming a green box must be a leaf. "do" ends in the middle of the path to "dog".

Quick check

  1. Why does a trie store "cat" and "car" with fewer boxes than two separate words?
    • It compresses letters into numbers
    • They share the boxes for the common prefix "ca"
    • It deletes the last letter
  2. What does the end flag on a node tell you?
    • A stored word finishes exactly at this node
    • This node has no children
    • This node is the root
  3. What does the root node of a trie hold?
    • The first letter of the first word
    • No letter, just the children of the first letters
    • The longest word