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.
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 words | Trie |
|---|---|
| Exact lookup O(L) average | O(L) |
| Prefix query: O(N·L) scan | O(P) walk + enumerate matches |
| Memory | can be large (one node per character); compress with radix trees |