Imagine you have a list of a thousand words — names, keywords, forbidden phrases — and a long text to scan. The obvious approach is to run a search for each word one at a time. If the text has n characters and the dictionary has k words, the naïve total is comparisons: fifty thousand passes through a fifty-page document.
In 1975, Alfred Aho and Margaret Corasick at Bell Labs published a single algorithm that does all the searching in time — where m is the total length of all patterns and z is the number of matches found. It doesn't matter how many patterns there are; you pay for each one only once, at build time.
The trick is to compile the dictionary into a finite automaton: a machine that reads the text one character at a time, keeps track of the longest dictionary prefix it has seen so far, and never backtracks. Each pattern match triggers a report; then the machine marches forward.
That guarantee — one character in, one state transition, guaranteed progress — is what makes Aho-Corasick feel almost miraculous. It was described as solved the moment the paper appeared: the algorithm is optimal in the worst case, and improvements since then are constants, not complexity classes.
Comments
Loading comments...