Skip to content
AdvancedAdvanced

Trie

A tree-like data structure where each node represents a character and paths from root to nodes form prefixes. Tries enable O(m) insert, search, and prefix queries (m = word length), making them ideal for dictionaries, autocomplete, spell checking, and word search problems where multiple strings share common prefixes.

Empty Trie

Start with an empty trie (root node only)

*
Regular Node
End of Word
Step 1/8
Speed:

When to Use

  • Prefix-based search
  • Autocomplete / word suggestions
  • Word search in a board
  • Longest common prefix

Key Indicators

  • Prefix matching
  • Dictionary/word search
  • Autocomplete
  • Multiple string queries

Complexity

Time

O(m) per operation (m = word length)

Space

O(total characters)

Common Problems

Implement TrieWord Search IIDesign Add and Search WordsLongest Word in Dictionary

Code

class TrieNode:
    children = {}
    is_end = False

def insert(word):
    node = root
    for char in word:
        if char not in node.children:
            node.children[char] = TrieNode()
        node = node.children[char]
    node.is_end = True

Want all 29 patterns with detailed visual walkthroughs?

The complete book includes 84 practice problems, full decision tree, and illustrated step-by-step solutions.

Book Coming Soon ($4.99)