DSA Master › Topic 16
Trie & String Algorithms
A trie stores strings character by character so that words with a common prefix share a path. Prefix lookups cost O(length of word). KMP finds a pattern in a text in O(n + m) using a failure table.
Concepts
- Trie construction
- Prefix matching
- KMP basics
- String searching
How to recognise it
- Many words need prefix lookups, or wildcard search.
- You're searching a grid for many words at once (Word Search II).
- You need substring search faster than O(n·m).
Common pitfalls
- In Word Search II, remove words from the trie once found. It avoids duplicates and speeds things up.
- Searching for a word and searching for a prefix differ: one checks the end flag, the other doesn't.
Problems
- Implement Trie (Prefix Tree) (Medium)
- Design Add and Search Words Data Structure (Medium)
- Word Search II (Hard)
- Find the Index of the First Occurrence in a String (Easy)
- Repeated String Match (Medium)