Aho-Corasick Algorithm
In computer science, the Aho-Corasick Algorithm is a string searching algorithm that efficiently finds multiple patterns in a given text. It constructs a finite-state machine in the form of a trie (prefix tree) with failure links, allowing it to search for all patterns simultaneously in linear time.
Overview
The Aho-Corasick Algorithm is a classical string matching algorithm used for efficiently finding multiple patterns within a given text. It constructs a finite-state machine in the form of a trie (prefix tree) with failure links, which allows it to search for all patterns simultaneously in linear time.
Video Explanation

Time Complexity:
- Construction Time: O(m), where
mis the total number of characters in all patterns. - Search Time: O(n), where
nis the length of the text.
How It Works
- Trie Construction: All patterns are inserted into a trie where each node represents a character in the patterns.
- Failure Links: Failure links are added to each node, pointing to the longest suffix which is also a prefix. This allows the algorithm to efficiently transition between nodes when a mismatch occurs.
- Pattern Search: The text is processed one character at a time, following the trie structure to match the patterns. If a mismatch occurs, failure links are used to skip unnecessary comparisons.
Example
Given patterns ["he", "she", "his", "hers"] and the text "ushers", the Aho-Corasick algorithm constructs a trie with failure links to search for these patterns. The algorithm finds matches for "he", "she", and "hers".