Skip to main content
Intermediate ~12 min read

Tries (Prefix Trees)

The tree built out of words themselves: O(L) insert and search, and the only structure that answers prefix queries natively.

Prerequisites: Binary Trees & Traversals, Hash Tables & Sets

A trie (prefix tree) stores strings by sharing their common prefixes. The root represents the empty string; each edge adds one character; walking root-to-node spells that node's prefix. A boolean flag marks nodes where a stored word ends. Insert "cat", "car", and "cart" and they share the c-a-r spine, branching only where they must, the structure is literally the vocabulary it holds.

Every operation costs O(L) where L is the word length, independent of how many words are stored. That is the trie's superpower: search a dictionary of a million words in the time it takes to spell one. A hash map also does O(L) exact lookups (hashing the string touches every character), but it cannot answer "which stored words start with 'car'?" without scanning everything. A trie answers by walking to the 'car' node and enumerating its subtree, the prefix query is native.

A minimal, complete trie

trie.js
class TrieNode {
  children = new Map();   // char → TrieNode
  isWord = false;
}

class Trie {
  root = new TrieNode();

  insert(word) {                      // O(L)
    let node = this.root;
    for (const ch of word) {
      if (!node.children.has(ch)) node.children.set(ch, new TrieNode());
      node = node.children.get(ch);
    }
    node.isWord = true;
  }

  search(word) {                      // O(L), exact match
    const node = this.walk(word);
    return node !== null && node.isWord;
  }

  startsWith(prefix) {                // O(L), prefix query, hash maps can't do this
    return this.walk(prefix) !== null;
  }

  walk(s) {
    let node = this.root;
    for (const ch of s) {
      node = node.children.get(ch);
      if (!node) return null;
    }
    return node;
  }
}

Cost summary

Operation / caseCostNotes
Insert / search / startsWithO(L)L = word length, independent of dictionary size
Enumerate prefix matchesO(L + matches)walk to prefix, DFS the subtree
SpaceO(total characters)prefix sharing shrinks it in practice; compressed tries (radix trees) shrink it further

Alphabet size affects the constant: 26 letters, but Map/HashMap children make Unicode natural at a small pointer cost.

Practice

A trie contains "car", "cat", "cart". How many nodes does the path for the prefix "car" visit, including the root?

Reveal explanation

Root (empty), then c, a, r, 4 nodes. The 't' of cat and 't' of cart branch only after the shared c-a-r spine.

Check your understanding

  1. 1.What does a trie's search cost depend on?
  2. 2.Which query is effectively impossible for a plain hash map but natural for a trie?
  3. 3.Phone T9 predictive text and browser address-bar autocomplete are classic applications of:

Finished reading?

Mark it complete to earn +50 XP. Progress stays in your browser.

Keep going