Skip to main content
Back to all problems
Beginner guide, Algorithms & data structures

Tries

A tree of characters for prefix search, built on what trees taught us.

A trie (also called a prefix tree, pronounced "try") is a tree that stores words. Each step down the tree is one letter, so a word is a path from the root. Words that start the same way share the same path for their common beginning.

What it looks like

The words car, card, care and cat:

Loading diagram...

c and a are stored only once, even though four words use them.

What a node holds

js
class TrieNode {
  children = new Map() // letter → next node
  isEnd = false // does a whole word end here?
}
  • children: where you can go next, one entry per letter.
  • isEnd: marks the end of a word. Without it, you couldn't tell the word car from the prefix ca on the way to cat.

The one move: walk the letters

Every trie operation is the same loop: start at the root and follow one letter at a time.

js
let node = root
for (const char of word) {
  node = node.children.get(char)
  if (!node) break // no stored word continues this way
}
OperationDuring the walkAt the end
insert a wordcreate any missing childset isEnd = true
search a wordmissing letter → falsereturn isEnd
startsWith a prefixmissing letter → falsereturn true

Why bother? Speed that ignores the dictionary's size

With L = the length of the word you're looking up:

QuestionList of wordsHash setTrie
Is this exact word stored?O(n · L)O(L)O(L)
Does any word start with this prefix?O(n · L)O(n · L)O(L)

A hash set is great for exact words, but useless for prefixes. A trie answers prefix questions in time that depends only on the prefix length, whether you've stored 10 words or 10 million.

The real superpower: pruning a search

When you're exploring letter by letter (a grid, wildcards, a sentence), the trie tells you at every step: "does any word still start like this?" If not, you stop exploring that branch immediately.

  • Design Add and Search Words: a . wildcard tries every child, but real letters follow one path.
  • Word Search II: a DFS on the board moves through the trie at the same time and abandons paths no word could follow.

How to recognize this category

  • The problem has a dictionary of words and asks about prefixes, autocomplete, or "starts with".
  • You're searching for many words at once (in a grid, a string or a stream).
  • Matching with wildcards, letter by letter.

Common mistakes

  • Forgetting isEnd, so a prefix is reported as a word.
  • Treating "the path exists" as "the word exists". That's startsWith, not search.
  • Not pruning. If you walk the trie but don't stop when a child is missing, you lose the whole benefit.

Practice what you learned

The problems go from easier to harder. Try each one on your own and open a hint when you get stuck.