![]() |
VOOZH | about |
Prerequisite:Aho-Corasick algorithm
Given a string and patterns, check for each pattern if it appears in the string.
Example:
Input: s = "aybabtu", patterns = {"bab", "abc", "ayba"}
Output: YES
NO
YESInput: s = "bybabtu", patterns = {"bat", "tu"}
Output:
NO
YES
Approach:
The solution uses a method called the Aho-Corasick algorithm. Let's see how it works:
- Building a Trie: We first create a special kind of tree called a ‘trie’ from the patterns we’re looking for. Each pattern is a path in the trie from the root to a node.
- Failure Links: We then add "failure links" to the trie. These links help us jump back efficiently in the trie when a character doesn’t match.
- Searching: We go through the given string, character by character, moving along the paths in the trie. If we reach the end of a path (a pattern), we know that pattern exists in the string.
- Counting: While searching, we keep track of how many times we reach each node (pattern). This tells us how many times each pattern appears in the string.
This method is fast because it checks all patterns at the same time, instead of one by one.
Steps-by-step approach:
Below is the implementation of the above approach:
YES NO YES
Time complexity: O(numPatterns * m + n + s), where: numPatterns is the number of patterns, m is the average length of the patterns, n is the total number of nodes in the trie, s is the length of the main string.
Auxiliary Space: O(n + numPatterns)