# Unraveling the Aho-Corasick String Matching Algorithm

Oct 9, 2023

The other day, I stumbled upon this algorithm and was truly captivated by its brilliance. I couldn’t resist the urge to share it with all of you, so here it is.

## A bit of historical background

The Aho-Corasick algorithm (hereinafter “A-C”) was conceived by Alfred V. Aho and Margaret J. Corasick. A-C was introduced in their seminal paper titled “Efficient string matching: An aid to bibliographic search,” published in 1975. This work was aimed at addressing the computational challenges associated with bibliographic search, which is a crucial aspect of academic research and literary work management.

During the 1970s, bibliographic search was emerging as a critical challenge, especially with the burgeoning volume of academic literature. The need for efficient string matching algorithms was glaring, as traditional approaches were notably inefficient when tasked with searching for multiple patterns within large text corpora.

A-C is built upon earlier theoretical work in automata theory and the theory of computation. It leverages the power of trie data structures and finite automata to perform efficient string matching. The algorithm’s elegance lies in its simplicity and efficiency, making a single pass over the text, regardless of the number of patterns.

## The Trie Structure

The journey begins with a data structure known as Trie, a type of search tree used to store a collection of strings. Each node in this tree represents a character, and a path from the root to a node spells out a word. This structure serves as the backbone of our algorithm, providing a map for the patterns we seek.

## Constructing the Trie

Given a set of words, say `{"he", "she", "his", "hers"}`, the algorithm constructs a Trie. This process is akin to creating a directory where each word gets its own unique address based on its characters. As each word is processed, it’s broken down into individual characters which guide the formation of branches in the Trie. The commonality between the starting characters of different words is utilized to create shared branches, thus optimizing the structure.

For example, the words “he” and “hers” both start with the character ‘h’, so they share the initial branch. As we move to the next character, new branches are formed to accommodate the differences. This setup ensures that each word has a unique path within the Trie, yet common prefixes are represented efficiently.

The algorithm then adorns the Trie with failure links, a mechanism to gracefully retreat and advance along different branches when a mismatch occurs. These links conect nodes in a manner that encapsulates the shared prefixes among the words, creating a network of fallbacks. It’s akin to having secret passages that swiftly guide the search to the right path upon encountering a hurdle.

## The Search Begins

With a well-prepared Trie, the search commences. As the algorithm traverses the text, it follows the branches of the Trie, character by character. Each match propels it deeper into the Trie, while a mismatch ushers it along the failure links to the next potential matching position. This dance continues, seamlessly transitioning between the text and the Trie, leaving no stone unturned.

## Harvesting the Matches

Whenever the traversal reaches the end of a word in the Trie, a match is found! The position of the match within the text is recorded, and the search marches on unfazed, in pursuit of other patterns.

## The result

At the conclusion of this expedition, the algorithm presents a comprehensive list of all ocurrences of the words within the text. A-C’s ability to find multiple patterns in a single pass makes it a cherished asset in the toolbox of text processing.

## Implementation

For those desiring a more tangible grasp, here is a TypeScript implementation of the Aho-Corasick algorithm.

We will start by defining the max number of states in `buildMatchingMachine` and the max number of characters in the alphabet.

Next we will define the `AhoCorasick class`, which will be responsible for constructing the Trie and performing the search.

And finally we will use the class to search for the words in a given text.