Skip to content

Implement Trie (Prefix Tree)

MediumLeetCode #208Time O(L)Space O(total chars)

Build a class Trie with three methods. insert(word) stores a word. search(word) returns true only if that exact word was inserted. startsWith(prefix) returns true if any inserted word begins with the prefix.

insert("apple") search("apple") -> true search("app") -> false
startsWith("app") -> true insert("app") search("app") -> true

“app” is a prefix of “apple” but was not inserted as a word, so search says false until it is.

A hash set answers search in O(L) for a word of length L, but startsWith forces you to scan every stored word. Brute force is O(total characters) per query.

Store the words as a tree instead: one character per edge, so words with the same beginning share one path. Each node keeps a map from character to child, plus a flag saying “a word ends here”. All three operations are the same walk from the root. Insert creates missing nodes and sets the flag at the end. search walks and checks the flag. startsWith walks and only checks that the path exists.

Show solutionHide solution
class TrieNode:
def __init__(self):
self.children = {} # char -> TrieNode
self.is_word = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word: str) -> None:
node = self.root
for ch in word:
if ch not in node.children:
node.children[ch] = TrieNode()
node = node.children[ch]
node.is_word = True
def search(self, word: str) -> bool:
node = self._find(word)
return node is not None and node.is_word
def starts_with(self, prefix: str) -> bool:
return self._find(prefix) is not None
def _find(self, s: str):
"""Follow s from the root; return the node it ends on, or None."""
node = self.root
for ch in s:
if ch not in node.children:
return None
node = node.children[ch]
return node
  • Time: O(L) — each of insert, search and startsWith touches one node per character of the argument, with O(1) map work per step (L = length of the word or prefix).
  • Space: O(total chars) — at most one node per inserted character; shared prefixes cost nothing extra.
  • Search and startsWith differ only in the flag. Forgetting is_word makes search("app") return true after inserting only “apple”.
  • Set the flag on the last node, not on every node on the path. Otherwise every prefix looks like a word.
  • Don’t build the node before checking. In search and startsWith, never create children while walking; only insert may add nodes.

Design Add and Search Words Data Structure (LeetCode 211)

Section titled “Design Add and Search Words Data Structure (LeetCode 211)”

Same trie, but search accepts . as a wildcard for any one letter. The trick: on a normal letter follow that child; on . try every child recursively (DFS). Insert is unchanged.

Find all words from a list that can be traced on a letter grid. The trick: put the words in a trie and run one DFS from each cell, walking the trie alongside the grid. Stop a path as soon as the trie has no child for the next letter; that pruning beats running Word Search once per word.

Replace each word in a sentence with its shortest dictionary root. The trick: insert the roots, then for each word walk the trie and return the prefix at the first node with is_word set. If the walk dies first, keep the original word.