Topic · 2 patterns
Strings & Tries patterns
Strings bring two patterns of their own. A trie stores words by their prefixes, for autocomplete, word search and XOR maximisation; string matching (KMP, the Z-function, Rabin-Karp) finds a pattern in a text in linear time instead of comparing at every position.
The patterns
Trie (Prefix Tree)
O(L) per op
A tree of characters; each path spells a prefix. Walk character by character to insert/search.
Spot it: Many words with prefix queries: autocomplete, startsWith, Replace Words, word search on a grid, or max XOR pair.
String Matching (KMP / Z / Rabin-Karp)
O(n + m)
Precompute a prefix-function (KMP) so a mismatch skips ahead without rescanning, or use a rolling hash.
Spot it: Find a pattern in text, longest prefix that is also a suffix (border), periodicity / repeated pattern, shortest palindrome by prepending.
Which one? Match the signal
| If the problem says | Reach for |
|---|---|
| Prefix matching, autocomplete/dictionary, word search on a grid, maximum XOR | Trie |
| Find a pattern inside a text efficiently, or detect repeated-substring structure | String Matching (KMP/Z) |
Used together
Bitmask DP + String Matching (KMP / Z / Rabin-Karp)
When: shortest superstring containing all words (n <= 12). Superstring length = total - sum of overlaps along an order.
Trie (Prefix Tree) + Backtracking
When: find all dictionary words in a grid. Running word-search per word repeats the same DFS.
Trie (Prefix Tree) + 1D / Fibonacci-style
When: word break / count segmentations with a big dictionary. Checking every dictionary word at every position is too slow.
FFT / NTT Convolution (and Walsh-Hadamard) + String Matching (KMP / Z / Rabin-Karp)
When: pattern matching with wildcards, or counting mismatches/near-matches for every alignment. With wildcards or mismatch tolerance, KMP's prefix function no longer applies, but the matches at every shift are a convolution.
Trie (Prefix Tree)
- Implement Trie (Prefix Tree)Medium
- Replace WordsMedium
String Matching (KMP / Z / Rabin-Karp)
- Find the Index of the First Occurrence in a StringEasy
- String MatchingMedium
Further reading
- Prefix function (KMP)cp-algorithms
Best KMP explanation; derivation not memorisation.
- Z-functioncp-algorithms
Simpler alternative to KMP for pattern matching.
- String hashingcp-algorithms
Polynomial rolling hash (Rabin-Karp) and collision handling.
- Trie explore cardLeetCode
Trie implementation and interview applications.
- String cheatsheetTech Interview Handbook
Anagram, palindrome and counting techniques.