Skip to main content
Trie Pattern

What is Trie?

Trie (prefix tree) is a tree-like data structure for storing strings where each node represents a character. It enables O(m) search/insert where m is string length.
Quick Recognition: Problems involving prefix matching, autocomplete, word dictionaries, or searching multiple words efficiently. Keywords: “prefix”, “dictionary”, “word search”, “autocomplete”.

Pattern Recognition Checklist

Use Trie When

  • Prefix-based search (autocomplete)
  • Word dictionary with wildcard search
  • Word search in 2D grid (multiple words)
  • Longest common prefix
  • Spell checking
  • IP routing (binary tries)

Don't Use When

  • Exact match only (use HashSet)
  • Single word search (use HashMap)
  • Memory is very constrained
  • Small dictionary (overhead not worth it)

Trie Complexity Reference

OperationTimeSpace
InsertO(m)O(m) per word
SearchO(m)-
Prefix searchO(m)-
DeleteO(m)-
Build trieO(n * m)O(n * m * 26) worst case
Where m = word length, n = number of words

When to Use

Autocomplete

Suggest words by prefix

Spell Checker

Find words with similar prefixes

Word Search

Search word in grid

Longest Prefix

Find longest common prefix

Basic Implementation

class TrieNode:
    def __init__(self):
        self.children = {}
        self.is_end = False

class Trie:
    def __init__(self):
        self.root = TrieNode()
    
    def insert(self, word):
        """Insert word into trie - O(m)"""
        node = self.root
        for char in word:
            if char not in node.children:
                node.children[char] = TrieNode()
            node = node.children[char]
        node.is_end = True
    
    def search(self, word):
        """Check if word exists - O(m)"""
        node = self._traverse(word)
        return node is not None and node.is_end
    
    def startsWith(self, prefix):
        """Check if any word has prefix - O(m)"""
        return self._traverse(prefix) is not None
    
    def _traverse(self, s):
        """Helper to traverse trie"""
        node = self.root
        for char in s:
            if char not in node.children:
                return None
            node = node.children[char]
        return node

Pattern Variations

1. Word Search II (Backtracking + Trie)

def find_words(board, words):
    """Find all words from dictionary in grid"""
    # Build trie from words
    trie = Trie()
    for word in words:
        trie.insert(word)
    
    rows, cols = len(board), len(board[0])
    result = set()
    
    def dfs(r, c, node, path):
        char = board[r][c]
        if char not in node.children:
            return
        
        node = node.children[char]
        path += char
        
        if node.is_end:
            result.add(path)
        
        board[r][c] = '#'  # Mark visited
        
        for dr, dc in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
            nr, nc = r + dr, c + dc
            if 0 <= nr < rows and 0 <= nc < cols and board[nr][nc] != '#':
                dfs(nr, nc, node, path)
        
        board[r][c] = char  # Restore
    
    for r in range(rows):
        for c in range(cols):
            dfs(r, c, trie.root, "")
    
    return list(result)

2. Autocomplete System

class AutocompleteSystem:
    def __init__(self, sentences, times):
        self.root = TrieNode()
        self.current_input = ""
        
        for sentence, count in zip(sentences, times):
            self._insert(sentence, count)
    
    def _insert(self, sentence, count):
        node = self.root
        for char in sentence:
            if char not in node.children:
                node.children[char] = TrieNode()
            node = node.children[char]
        node.is_end = True
        node.count = getattr(node, 'count', 0) + count
    
    def input(self, c):
        if c == '#':
            self._insert(self.current_input, 1)
            self.current_input = ""
            return []
        
        self.current_input += c
        return self._search(self.current_input)
    
    def _search(self, prefix):
        node = self.root
        for char in prefix:
            if char not in node.children:
                return []
            node = node.children[char]
        
        # DFS to find all sentences with this prefix
        results = []
        self._dfs(node, prefix, results)
        
        # Sort by count (desc), then lexicographically
        results.sort(key=lambda x: (-x[1], x[0]))
        return [s for s, _ in results[:3]]
    
    def _dfs(self, node, path, results):
        if node.is_end:
            results.append((path, node.count))
        for char, child in node.children.items():
            self._dfs(child, path + char, results)

Classic Problems

ProblemPatternKey Insight
Implement TrieBasic opsHashMap children
Word Search IITrie + DFSPrune with trie
AutocompleteTrie + HeapTop-k by frequency
Longest WordBFS/DFSCheck prefixes exist
Word DictionaryTrie + ’.’DFS for wildcards

Interview Problems by Company

ProblemCompanyKey Concept
Implement TrieAll FAANGBasic trie ops
Word DictionaryMeta, AmazonWildcard DFS
Replace WordsAmazonPrefix replacement
Map Sum PairsGoogleTrie with values

Interview Tips

Script for interviews:
  1. “I’ll use a Trie for efficient prefix-based operations.”
  2. “Each node has children (HashMap or array of 26).”
  3. “I’ll mark end-of-word with a boolean flag.”
  4. “Insert and search are both O(word length).”
  5. “For Word Search II, I’ll combine Trie with DFS backtracking.”
ImplementationProsCons
HashMap childrenFlexible, sparse-friendlySlightly slower
Array[26]Faster accessWastes memory for sparse
With countSupports frequencyExtra space
With wordStore full word at endEasier retrieval
  1. Remove word from trie after finding (Word Search II)
  2. Store word at end node instead of just boolean
  3. Track count for frequency-based problems
  4. Prune empty branches after deletion

Practice Problems

Practice Roadmap

1

Day 1: Basic Trie

  • Solve: Implement Trie, Longest Common Prefix
  • Focus: Insert, search, startsWith operations
2

Day 2: Pattern Matching

  • Solve: Word Dictionary, Replace Words
  • Focus: Wildcard handling, prefix matching
3

Day 3: Trie + DFS

  • Solve: Word Search II
  • Focus: Combining trie with backtracking
4

Day 4: Advanced Trie

  • Solve: Autocomplete System, Palindrome Pairs
  • Focus: Ranking, complex traversals
Interview Tip: When you see multiple string searches or prefix operations, think Trie. It’s especially powerful when combined with DFS for grid problems.