Skip to content
DSA Patterns
Menu
Language

Pattern #18

Trie

Recommended

Prefix trees for dictionaries, word search, and shared prefixes.

When to use

Many strings share prefixes, or you need startsWith / autocomplete / board word search over a dictionary.

Recognition cues

  • Implement trie / add and search words
  • Word search II
  • Replace words / longest word in dictionary

Common pitfalls

  • Forgetting end-of-word mark vs mere prefix
  • Not sharing nodes (memory blow-up)
  • Mutating board without restoring in word search

90-second recognition drill

Which pattern fits best?

  • Implement trie / add and search words
  • Word search II
  • Replace words / longest word in dictionary

Interactive

Mental model

A full worked walkthrough of the invariant. Pause, scrub the dots, or use ← →. Aim to narrate each step yourself.

Step 1 of 8
1/8

Empty trie. Insert app, apple, bat.

∅root
Statewords=app, apple, bat
Key:CurrentActive rangeMatchSettled

How to think about it

Each edge is a character; a path from the root is a prefix. Nodes store children map (or array of 26) and an isWord flag. Insert walks/creates edges; search requires isWord; startsWith only needs the path to exist.

Template shapes

Shape Core move Example
Map trie insert creates the missing edge and marks the last node. search requires that mark. startsWith returns once the walk stays on the trie LC 208
Wildcard The same trie. A letter follows one child. A dot tries every child. The walk succeeds when the last character lands on a marked node LC 211
Board DFS steps only along trie edges. Mark the cell, try four neighbors, then restore the letter. Recording a word can drop trie nodes that no longer lead anywhere LC 212
Maximum XOR A binary trie from bit 31 down to 0. Insert a number, then query it. The walk takes the opposite bit when that child exists LC 421
Replace words Walk until a node is marked and replace the word with the path so far. A walk that leaves the trie keeps the original word LC 648
Longest word Sort longest first, then lexicographically. A word counts when every shorter prefix is in the set. The first word that passes is the answer. The write-up uses that set, which is the trie idea without the nodes LC 720

Complexity baseline

Insert/search O(L) in word length. Space O(total characters) across inserts. LC 720 sorts the dictionary first, O(n log n) in the number of words.

From template to problem

  1. search needs the end mark. startsWith returns when the walk stays on the trie (LC 208).
  2. A dot tries every child. A letter follows one (LC 211).
  3. Board DFS restores the cell. Recording a word may drop trie nodes that no longer lead anywhere (LC 212).
  4. Maximum XOR walks bits 31 down to 0 and prefers the opposite bit (LC 421). Longest word on this page sorts longest first and checks shorter prefixes in a set (LC 720).

Template

Same skeleton in TypeScript, Python, and C#. Adapt the invariant; keep the structure.

Trie · Template
/** Trie template: insert / search / startsWith. */
export class TrieNode {
  children = new Map<string, TrieNode>();
  isWord = false;
}
export class Trie {
  root = new TrieNode();
  insert(word: string): void {
    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: string): boolean {
    const node = this.walk(word);
    return Boolean(node?.isWord);
  }
  startsWith(prefix: string): boolean {
    return this.walk(prefix) != null;
  }
  private walk(s: string): TrieNode | null {
    let node: TrieNode | null = this.root;
    for (const ch of s) {
      if (!node!.children.has(ch)) return null;
      node = node!.children.get(ch)!;
    }
    return node;
  }
}
/** Trie template: insert / search / startsWith. */
export class TrieNode {
  children = new Map<string, TrieNode>();
  isWord = false;
}
export class Trie {
  root = new TrieNode();
  insert(word: string): void {
    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: string): boolean {
    const node = this.walk(word);
    return Boolean(node?.isWord);
  }
  startsWith(prefix: string): boolean {
    return this.walk(prefix) != null;
  }
  private walk(s: string): TrieNode | null {
    let node: TrieNode | null = this.root;
    for (const ch of s) {
      if (!node!.children.has(ch)) return null;
      node = node!.children.get(ch)!;
    }
    return node;
  }
}