CodeMosa

Master LeetCode Patterns

Trie

Prefix tree for fast prefix queries, dictionary word search, and bitwise tricks

Time: O(L)
Space: O(ALPH*nodes)

What is Trie?

#
Definition: A prefix tree that stores strings/bits along edges to share prefixes and support fast prefix queries.

Core Idea

#

Store characters/bits along paths to share common prefixes and support fast prefix checks.

When to Use

#

Use for autocomplete, word search, and maximum XOR of pairs using bitwise trie.

How Trie works

#

Insert/search/startsWith over node maps with end flags; bitwise trie variant stores bits for max-XOR queries.

  • Prefix search
  • Dictionary lookups
  • Bitwise XOR

General Recognition Cues

#
General indicators that this pattern might be applicable
  • Prefix search
  • Dictionary lookups
  • Bitwise XOR
#
Curated practice sets for this pattern

Code Templates

#
Insert/search/startsWith over node maps with end flags; bitwise trie variant stores bits for max-XOR queries.
# Trie Template
class TrieNode:
    def __init__(self):
        self.children = {}
        self.end = False

class Trie:
    def __init__(self): self.root=TrieNode()
    def insert(self, word):
        cur=self.root
        for ch in word:
            if ch not in cur.children: cur.children[ch]=TrieNode()
            cur=cur.children[ch]
        cur.end=True
    def search(self, word):
        cur=self.root
        for ch in word:
            if ch not in cur.children: return False
            cur=cur.children[ch]
        return cur.end
    def startsWith(self, pref):
        cur=self.root
        for ch in pref:
            if ch not in cur.children: return False
            cur=cur.children[ch]
        return True

Pattern Variants & Approaches

#
Different methodologies and implementations for this pattern
1
#

Standard char trie

When to Use This Variant
  • StartsWith
  • Insert/search
Use Case
Autocomplete
Advantages
  • O(L)
  • Shared prefixes
Implementation
class TrieNode:
    def __init__(self): self.children = {}; self.end=False
class Trie:
    def __init__(self): self.root=TrieNode()
    def insert(self, word):
        node=self.root
        for ch in word: node=node.children.setdefault(ch, TrieNode())
        node.end=True
    def search(self, word):
        node=self.root
        for ch in word:
            if ch not in node.children: return False
            node=node.children[ch]
        return node.end
    def startsWith(self, prefix):
        node=self.root
        for ch in prefix:
            if ch not in node.children: return False
            node=node.children[ch]
        return True
2

Autocomplete

#

Prefix traversal to collect words

When to Use This Variant
  • Prefix suggestions
Use Case
Suggest words
Advantages
  • Predictive
  • Bounded by output
Implementation
def autocomplete(trie, prefix):
    # trie: instance of Trie above
    def node_for(prefix):
        n = trie.root
        for ch in prefix:
            if ch not in n.children: return None
            n = n.children[ch]
        return n
    def dfs(node, path, out):
        if node.end: out.append(''.join(path))
        for ch, nxt in node.children.items():
            path.append(ch); dfs(nxt, path, out); path.pop()
    node = node_for(prefix)
    res = []
    if node: dfs(node, list(prefix), res)
    return res
3

Bitwise XOR Trie

#

Trie over bits for max XOR

When to Use This Variant
  • Max XOR pair
Use Case
XOR optimization
Advantages
  • O(32n)
  • Deterministic
Implementation
# Simple bitwise trie using dicts for max XOR query
class BitTrie:
    def __init__(self): self.root={}
    def insert(self, num):
        n=self.root
        for i in range(31,-1,-1):
            b=(num>>i)&1
            if b not in n: n[b]={}
            n=n[b]
    def max_xor(self, num):
        n=self.root; ans=0
        for i in range(31,-1,-1):
            b=(num>>i)&1; t=1-b
            if t in n: ans|=(1<<i); n=n[t]
            else: n=n.get(b, {})
        return ans

Common Pitfalls

#
Watch out for these common mistakes
  • Memory overhead
  • Cleaning up nodes on delete
  • Case sensitivity/Unicode

Example Problems

#
Classic LeetCode problems using this pattern

Complexity Analysis

#
Time Complexity
O(L)

L is word length.

Space Complexity
O(ALPH*nodes)

Nodes per unique prefix.

Ready to test your knowledge?

Test your pattern recognition with interactive questions