Tries & String Matching
Store sets of strings in a trie to answer prefix queries and power autocomplete, and find patterns in text in linear time.
4 objectives 6 steps about 130 min
Check what you know
The lessons are coming later. The knowledge check is ready now.
This skill page is a public outline. Its lessons and knowledge check appear here as subject-matter experts approve them.
Learning objectives
- Implement a trie with insert, exact search and starts-with queries using dict-based children and an end-of-word marker.
- Return the top-k completions for a prefix by combining trie traversal with stored counts or a heap.
- Compare a trie with a hash set and a sorted list plus bisect on memory and supported queries, and pick one for a given workload.
- Find every occurrence of a pattern in O(n + m) time with the KMP prefix function and with a Rabin-Karp rolling hash, explaining why naive search can cost O(nm) and how hash matches are confirmed.
Lesson plan
6 steps, about 130 min · 0 of 5 lessons available so far
- Sharing Prefixes in a Tree Concept · 15 min · coming later
- Lab: Insert, Search, Starts-With Lab · 25 min · coming later
- Autocomplete with Ranked Suggestions Worked example · 25 min · coming later
- Trie, Hash Set, Sorted List or Suffix Array? Concept · 20 min · coming later
- Pattern Search Without Rescanning: Prefix Function and Rolling Hash Worked example · 30 min · coming later
- Check: Prefix and Pattern Search Problems Knowledge check · 8 questions
Practise it
Load a 100,000-word frequency list into a trie, return the five most frequent completions for any prefix, and compare memory use and query time against a sorted list with a bisect-based prefix scan; then implement KMP and Rabin-Karp search and verify both against a brute-force scan on 1,000 random texts, including overlapping matches.
References
Hard prerequisites
Unlocks
On these roadmaps
Progress and evidence for this skill are shared across all of them.