String Matching and Text Search Basics
Understand naive substring search, text normalization (case folding, Unicode), and classical algorithms like KMP and Boyer-Moore. See why O(total_chars) per query is unsustainable and why precomputation via indexing is necessary.
The stumper
Searching 5,000 documents with includes feels instant. Searching 5 million documents with the same approach would take hours. Why?
The simplest approach is exhaustive: for each query, scan every document character by character looking for the pattern. This is correct and easy to understand. For tiny corpora it works fine.
As the corpus grows, linear scan becomes catastrophic. With 5M documents averaging 1KB each, you are examining billions of characters per query. CPU time, memory bandwidth, and latency all become blockers. At web scale this is impossible.
Classical string algorithms improve matching within a single document. KMP avoids re-scanning by using a prefix function to skip redundant comparisons. Boyer-Moore can skip large chunks by scanning from right to left and using bad-character/good-suffix heuristics. But even the best in-document algorithm still requires examining documents - the real fix is to never scan irrelevant documents at all via an index.
Before any matching, we must normalize: case folding makes "Apple" and "apple" equivalent, Unicode normalization (NFKC/NFC) handles composed vs decomposed characters, and sometimes we strip diacritics. Inconsistent normalization creates invisible failures.
Try it before you read on
Open the Lab tab. Change a parameter, break something, and form a hypothesis before reading the explanation.
Checkpoint
3 questions. Explanations appear after submission.
1. Why does a naive substring scan fail at large scale?
2. Why normalize Unicode and case before matching?
3. What is the Big Idea that replaces scanning?