Skip to content

Start typing to search patterns, problems and pages.

Tries

Start typing a word and your phone narrows the guesses with every letter. After two letters you are already on the right page for every word that starts that way. A trie stores words the same way, sharing each prefix once so a lookup only walks the letters you type.

⏱ about 15 minutesNeeds: trees, hash mapsTime O(L)Space O(total letters)

2 · Watch

Tries in 60 seconds

Searching a word list means comparing the query with every word. “car”, “cat” and “cart” all start the same, so the same letters get read again and again.

3 · Now you drive

Keys:←→ stepSpace playR resetHomeEnd jump

Implement Trie (Prefix Tree)

or try
Up to 4 words of 1–6 letters (a–z), then | and a word to look up.
Start with an empty root.Step 1 of 18. Empty trie, just a root node. 3 words to insert, then look up “ca”.
Step 1 of 18
solution.ts
class TrieNode {
children = new Map<string, TrieNode>();
isWord = false;
}
function insert(root: TrieNode, word: string) {
let node = 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;
}
function search(root: TrieNode, word: string, prefix = false) {
let node = root;
for (const ch of word) {
const next = node.children.get(ch);
if (!next) return false;
node = next;
}
return prefix || node.isWord;
}
▶ marks the line running now

4 · Your turn

0 of 3 problems solved

Start from this

let node = root;
for (const ch of word) {
  // Make the path if this letter isn't there yet.
  if (!node.children.has(ch)) {
    node.children.set(ch, new TrieNode());
  }
  node = node.children.get(ch)!;
}
// Without this, "app" matches because of "apple".
node.isWord = true;

Easy ways to go wrong

  • Forgetting the end-of-word flag, so “app” matches because “apple” exists.
  • Reaching for a trie when a plain set of words is enough.
  • Not pruning used words in board searches, which repeats the work.
  1. Medium01

    Implement Trie (Prefix Tree)

    LeetCode 208 · Blind 75 · NeetCode 150

    The one you just watched. Write it from memory.

  2. Medium02

    Design Add and Search Words Data Structure

    LeetCode 211 · Blind 75 · NeetCode 150

    Trie search where “.” matches any letter at that spot.

  3. Hard03

    Word Search II

    LeetCode 212 · Blind 75 · NeetCode 150

    Walk the board and the trie together, pruning dead letters.

UP NEXT · LESSON 11 OF 20HeapsAlways know the smallest or largest item.