Trie

A tree of characters where each path from the root spells a key, so prefix searches like autocomplete take time proportional to the prefix, not the dataset.

Description

A trie (from retrieval, often pronounced "try") stores strings character by character. Each edge is a character, each node a prefix, and a flag marks nodes where a complete word ends. Words that share a prefix share the same path: "car", "cart" and "cat" all start with the nodes for c and a.

To look up a word, follow its characters from the root. The cost depends on the length of the word, not on how many words are stored. More importantly, every word starting with a given prefix lives in one subtree, so prefix queries are natural: find the node for "ca" and collect everything below it.

That makes tries the classic structure for autocomplete, spell checking, IP routing tables (longest-prefix match on bits), and word games. The cost is memory: many nodes each holding a map of children. Radix trees (compressed tries) merge chains of single-child nodes to save space.

How it works

trtacgod•

A trie for car, cart, cat, do and dog. Highlighted nodes end a word.

  1. • → c, d
  2. c → a
  3. a → r, t
  4. r → t
  5. t
  6. t
  7. d → o
  8. o → g
  9. g
A trie for car, cart, cat, do and dog. Highlighted nodes end a word.

Complexity

OperationAverageWorst
Insert a word of length LO(L)O(L)
Look up a wordO(L)O(L)
Find all words with a prefixP is the prefix length, k the size of the output.O(P + k)O(P + k)
Delete a wordO(L)O(L)

Space: O(total characters), often with a large constant per node

Lookups don't depend on the number of stored words, which is the trie's advantage. Memory overhead per node is its weakness; compressed tries and arrays instead of maps help.

TypeScript implementation

A trie with insert, lookup and autocomplete, using a Map of children at each node.

trie.ts
// A trie with insert, lookup and autocomplete.

class TrieNode {
  children = new Map<string, TrieNode>();
  isWord = false;
}

export class Trie {
  private root = new TrieNode();
  nodes = 1;

  insert(word: string): void {
    let node = this.root;
    for (const ch of word) {
      let next = node.children.get(ch);
      if (!next) {
        next = new TrieNode();
        node.children.set(ch, next);
        this.nodes++;
      }
      node = next;
    }
    node.isWord = true;
  }

  private find(prefix: string): TrieNode | null {
    let node: TrieNode | undefined = this.root;
    for (const ch of prefix) {
      node = node.children.get(ch);
      if (!node) return null;
    }
    return node;
  }

  has(word: string): boolean {
    return this.find(word)?.isWord ?? false;
  }

  /** Every stored word that starts with prefix, in alphabetical order. */
  complete(prefix: string, limit = 10): string[] {
    const start = this.find(prefix);
    const out: string[] = [];
    const walk = (node: TrieNode, path: string) => {
      if (out.length >= limit) return;
      if (node.isWord) out.push(path);
      for (const ch of [...node.children.keys()].sort()) walk(node.children.get(ch)!, path + ch);
    };
    if (start) walk(start, prefix);
    return out;
  }
}

export function demo(): string[] {
  const t = new Trie();
  for (const w of ["car", "cart", "cat", "catalog", "do", "dog", "dot", "door"]) t.insert(w);
  return [
    `has "cat": ${t.has("cat")}, has "ca": ${t.has("ca")}`,
    `complete "ca" → ${t.complete("ca").join(", ")}`,
    `complete "do" → ${t.complete("do").join(", ")}`,
    `8 words share prefixes in ${t.nodes} nodes`,
  ];
}

When to use it

Use it when

  • Autocomplete and prefix search.
  • Spell checking and word games, where you explore valid prefixes.
  • Longest-prefix matching, as in IP routing and URL routers.

Avoid it when

  • You only need exact lookups: a hash table uses less memory and is simpler.
  • Keys are long and share few prefixes, so the trie saves nothing.
  • Memory is tight: use a sorted array of words with binary search for prefixes instead.

Pitfalls

  • Memory blow-up from one map or array per node. Compress chains or use arrays for small alphabets.
  • Forgetting the end-of-word flag, so "ca" appears as a word because "cat" exists.
  • Unicode: splitting strings by UTF-16 code units breaks characters outside the basic plane. Iterate by code points.

Alternatives

Hash table

Choose it when you never need prefix queries.

Balanced search tree

Choose it when you need ordered strings and range queries with less memory.

Search engine index

Choose it when you need fuzzy, full-text or ranked search, such as Elasticsearch or OpenSearch.