sagelearnai

Tries

Signal: many words with prefix queries (autocomplete, "starts with"), wildcard matching, searching a board for many words at once, or longest-common-prefix questions.

Core idea: a trie (prefix tree) stores strings character by character along paths from the root. Each node has children keyed by character and an end flag marking where a word finishes. Insert and lookup cost O(L) for a word of length L, independent of how many words are stored, and words sharing a prefix share nodes.

root c d a o t r g words: cat, car, dog (green = end of a word). "ca" is a prefix shared by cat and car.
python
class TrieNode:
    __slots__ = ("children", "end")
    def __init__(self):
        self.children = {}      # char -> TrieNode  (or a 26-slot array)
        self.end = False

def insert(root, word):
    node = root
    for ch in word:
        node = node.children.setdefault(ch, TrieNode())
    node.end = True
vs. hash set of wordsTrie
Exact lookup O(L) averageO(L)
Prefix query: O(N·L) scanO(P) walk + enumerate matches
Memorycan be large (one node per character); compress with radix trees

Problems

  1. Implement Trie (Prefix Tree) (Medium): Nodes with children map + end flag
  2. Design Add and Search Words Data Structure (Medium): Trie + DFS branching on '.'
  3. Replace Words (Medium): Trie of roots; walk each word until the first root ends
  4. Word Search II (Hard): Trie of words + one DFS over the board, pruning by prefix
  5. Longest Word in Dictionary (Medium): A word counts only if every prefix is a word; sort, or DFS a trie through end-nodes only
  6. Map Sum Pairs (Medium): Trie nodes store the running sum of all keys below them; apply deltas on overwrite
  7. Search Suggestions System (Medium): Sort products; the prefix matches form a contiguous range → binary search
  8. Maximum XOR of Two Numbers in an Array (Medium): Binary trie of bits; for each number greedily walk the opposite bit