Tries — Master Recap & Cheatsheet

Sanjeev SharmaSanjeev Sharma
3 min read

Advertisement

Tries Master Cheatsheet


Core Operations Complexity

OperationTimeSpace
Insert wordO(L)O(L * 26) array, O(L) hashmap
Search wordO(L)O(1)
Prefix checkO(L)O(1)
Word Search IIO(MN3^L) prunedO(sum lens)
Max XOR pairO(32*n)O(32*n)

Standard Trie Template

class TrieNode:
    def __init__(self):
        self.children = {}  # or [None]*26
        self.is_end = False
        # Optional extras:
        # self.count = 0      # words through this node
        # self.word = ""      # word ending here (for Word Search II)

Binary Trie (XOR) Template

def insert(n, root):
    node = root
    for bit in range(31, -1, -1):
        b = (n >> bit) & 1
        if b not in node: node[b] = {}
        node = node[b]

def max_xor_query(x, root):
    node = root; xr = 0
    for bit in range(31, -1, -1):
        b = (x >> bit) & 1; want = 1 - b
        if want in node: xr = (xr << 1) | 1; node = node[want]
        else: xr <<= 1; node = node[b]
    return xr

Decision Guide

Need prefix search?Trie (vs HashSet)
Multiple words in grid?Trie + Grid DFS (Word Search II)
Autocomplete?Trie + sorted lists at each node
Max/Min XOR?Binary Trie (bit by bit)
Suffix matching?Reversed Trie
Words counted by prefix?Trie with count field
Combined prefix + suffix?Concatenate suf#pref as key

Problem Index

#ProblemKey Trick
01Implement TrieBasic insert/search/prefix
02Design Add Search WordsWildcard DFS with '.'
03Word Search IITrie pruning in grid DFS
04Replace WordsFirst '#' found = root
05Maximum XOR Two NumbersBinary trie greedy
06Search SuggestionsSort + bisect or trie lists
07Longest Word in DictionaryOnly traverse is_end nodes
08Palindrome PairsHashMap prefix/suffix check
09Stream of CharactersReverse trie + active nodes
10Prefix and Suffix Searchsuf#pref concatenated key
11Sum of Prefix Scorescount at each trie node
12Concatenated WordsWord break DP + word_set
16Max XOR with ElementOffline sort + binary trie

Advertisement

Sanjeev Sharma

Written by

Sanjeev Sharma

Full Stack Engineer · E-mopro