This is a great question about the Aho-Corasick algorithm. Let me provide a comprehensive explanation of the failure link construction, with examples and code.
The Aho-Corasick algorithm is a string matching algorithm that can search for multiple patterns in a text efficiently. Key components:
- Trie Construction: Build a trie from all patterns
- Failure Link Construction: Build failure functions (similar to KMP failure function but for trie)
- Text Scanning: Traverse the trie with failure links to find all pattern matches
Let me break this down:
Understanding Failure Links
In KMP, the failure function tells us where to continue if a mismatch occurs. In Aho-Corasick, failure links do something similar but for a trie structure.
A failure link from node u points to the node v such that:
- The string represented by the path to
v is the longest proper suffix of the string represented by the path to u
- That suffix is also a prefix of some pattern (i.e.,
v is reachable following the trie from root)
Construction Algorithm
- Root's failure link points to itself
- Use BFS from root, processing nodes level by level
- For each node, calculate failure link based on:
- Its parent's failure link
- The character used to reach it
Let me provide a detailed implementation with explanation:
class AhoCorasickNode:
def __init__(self):
self.children = {} # char -> node
self.fail = None # failure link
self.is_end = False # is this a pattern ending
self.pattern_id = -1 # which pattern ends here
self.output = [] # all patterns ending at this node
class AhoCorasick:
def __init__(self):
self.root = AhoCorasickNode()
def add_pattern(self, pattern, pattern_id):
"""Add a pattern to the trie"""
node = self.root
for char in pattern:
if char not in node.children:
node.children[char] = AhoCorasickNode()
node = node.children[char]
node.is_end = True
node.output.append(pattern_id)
def build_failure_function(self):
"""Build failure links using BFS"""
from collections import deque
queue = deque()
# Root's failure link points to itself
self.root.fail = self.root
# Initialize first level: direct children of root have failure links pointing to root
for child in self.root.children.values():
child.fail = self.root
queue.append(child)
# Process remaining levels
while queue:
current = queue.popleft()
for char, child in current.children.items():
queue.append(child)
# Find failure link for child
fail_node = current.fail
while fail_node != self.root and char not in fail_node.children:
fail_node = fail_node.fail
child.fail = fail_node.children.get(char, self.root)
# Accumulate patterns from failure link
if child.fail.is_end:
child.output.extend(child.fail.output)
The failure function construction works by processing nodes level-by-level using BFS. For each node, we follow its parent's failure link until we find a node that has a child with the same character, or we reach the root. This ensures we find the longest suffix that's also a prefix in the trie structure. I need to complete the partial thought about building the AC automaton with a concrete example.
The trie for patterns "he", "she", "his", "hers" has root with children h and s. From h, we branch to e (marking end of "he") and i. The i node has child s (marking end of "his"). From root's s child, we get h, which leads to e (marking end of "she"), and that e node has child r leading to s (marking end of "hers").
During BFS construction, depth-1 nodes h and s point their fail links to root. For depth-2 nodes, when processing h's child e, we follow h's fail link (root) and find e isn't in root's children, so e's fail link points to root. Similarly, i's fail link points to root since root has no i child. The s child of root's s gets its fail link by checking root's children for s, finding it, so it points there. This cascades through remaining nodes, with each failure link either pointing to an existing node or back to root, and output sets merge matches from failure destinations. The trie structure uses nodes with goto links for each character and failure links for the automaton. Each node tracks whether it marks a pattern end and stores matching pattern IDs.
To build the automaton, I need to construct failure links using BFS. Starting from the root with its failure pointing to itself, I process nodes level by level. For each node, the failure link points to the longest proper suffix that exists in the trie, found by following the parent's failure link and checking for the current character. Once failure links are established, I can merge output sets so each node includes patterns from its failure link chain.
During search, I traverse the text character by character. When a character isn't available from the current state, I follow failure links back until finding a valid transition or reaching root. After each move, I check the current node's output for any pattern matches at that position.
The example demonstrates this with text "ushers" and patterns ["he", "she", "his", "hers"]. As I process each character, the automaton identifies when patterns end, recording their positions and IDs for later retrieval. node(2) [his -> s], node(7).fail = node(3) [she -> he], node(8).fail = node(0) [sher -> root], and node(9).fail = node(2) [shers -> s].
When searching "ushers", the automaton starts at the root. At position 0, 'u' has no transition so it remains at root. Moving to position 1, 's' transitions to the s_node. At position 2, 'h' moves to the sh_node.
Continuing forward, position 3 encounters 'e' which transitions to she_node and triggers a match for "she" ending at index 3. At position 4, 'r' advances to sher_node with no pattern match. Finally at position 5, 's' reaches shers_node, matching "hers" which ends at index 5.
Aho-Corasick Failure Link Construction
The Aho-Corasick algorithm enables multi-pattern matching in linear time O(n + m + z), where n = text length, m = total pattern length, and z = number of matches.
Core Concept: Failure Links
A failure link from node u points to node v where:
- The path string to
v is the longest proper suffix of path to u
- That suffix is also a valid prefix in the trie
Patterns: ["he", "she", "his", "hers"]
root
/ \
h s
/ \ |
e i h
◆ | |
s e
◆ |
r
|
s
◆ (◆ = pattern end)
Failure links example:
- "sh" → "h" (sh suffix = h, h is valid prefix)
- "shers" → "s" (shers suffix = s, s is valid prefix)
Implementation
from collections import deque
class TrieNode:
def __init__(self):
self.goto = {} # transition map: char -> node
self.fail = None # failure link
self.output = [] # pattern IDs ending here
self.is_pattern_end = False
class AhoCorasick:
def __init__(self):
self.root = TrieNode()
self.patterns = []
def add_pattern(self, pattern):
"""Step 1: Build trie from all patterns"""
node = self.root
for char in pattern:
if char not in node.goto:
node.goto[char] = TrieNode()
node = node.goto[char]
if not node.is_pattern_end:
node.is_pattern_end = True
pattern_id = len(self.patterns)
self.patterns.append(pattern)
node.output.append(pattern_id)
def build_failure_function(self):
"""Step 2: Construct failure links using BFS"""
queue = deque()
# Level 0: Root's failure link points to itself
self.root.fail = self.root
# Level 1: Direct children of root fail to root
for char, node in self.root.goto.items():
node.fail = self.root
queue.append(node)
# Level 2+: Process nodes level-by-level (BFS)
while queue:
current = queue.popleft()
# For each child of current node
for char, child in current.goto.items():
queue.append(child)
# Find failure link: follow parent's failure links
# until we find a node with this transition
fail_node = current.fail
while fail_node != self.root and char not in fail_node.goto:
fail_node = fail_node.fail
# Set child's failure link
if char in fail_node.goto:
child.fail = fail_node.goto[char]
else:
child.fail = self.root
# Important: Merge output from failure link
# (handles overlapping/suffix patterns)
if child.fail.output:
child.output.extend(child.fail.output)
def search(self, text):
"""Step 3: Scan text in linear time"""
matches = []
current = self.root
for i, char in enumerate(text):
# Follow failure links until valid transition found
# or reach root (guarantees progress)
while current != self.root and char not in current.goto:
current = current.fail
# Move to next state
if char in current.goto:
current = current.goto[char]
else:
current = self.root
# Report all patterns matching at this position
if current.output:
for pattern_id in current.output:
# Calculate actual start position
pattern_len = len(self.patterns[pattern_id])
start_pos = i - pattern_len + 1
matches.append({
'pattern': self.patterns[pattern_id],
'end_pos': i,
'start_pos': start_pos
})
return matches
Step-by-Step Example
Building the Automaton
Patterns: ["he", "she", "his", "hers"]
Trie after pattern insertion:
root(0)
/ \
h(1) s(2)
/ \ |
e i h(3)
| | |
[0] s e(4)
| |
[2] r(5)
|
s(6)
|
[3]
Failure Link Construction:
| Node | Depth | Path | Failure Link | Logic |
|---|
| root | 0 | ε | root | Root→Root |
| h | 1 | h | root | No proper suffix |
| s | 1 | s | root | No proper suffix |
| e (he) | 2 | he | root | Suffix "e" not in trie |
| i (hi) | 2 | hi | root | Suffix "i" not in trie |
| h (sh) | 2 | sh | h | Suffix "h" = node h |
| s (his) | 3 | his | s | Suffix "s" = node s |
| e (she) | 3 | she | e | Suffix "he" = path to e |
| r (sher) | 4 | sher | root | Suffix "r" not in trie |
| s (shers) | 5 | shers | s | Suffix "s" = node s |
Text Scanning Example
Text: "ushers"
Trace:
Position Char Current State Output
────────────────────────────────────────────
Start - root -
0 u root (no 'u')
1 s s_node
2 h sh_node
3 e she_node ✓ "she" (id=1)
4 r sher_node
5 s shers_node ✓ "hers" (id=3)
Results:
- "she" at position 1-3
- "hers" at position 2-5
Key Advantages
# Why failure links matter:
# Without failure links (naive approach):
# - Must restart from root on mismatch: O(nm) worst case
# - Example: searching "mississippi" for ["mississippi"]
# would reset at each mismatch
# With failure links:
# - Never backtrack in text
# - Linear progression through text: O(n)
# - Make progress even on failed matches
# Time Complexity:
# - Build trie: O(m) where m = sum of pattern lengths
# - Build failure function: O(m)
# - Search: O(n + z) where z = total matches
# Total: O(m + n + z) ✓ Linear!
Practical Implementation with Real-World Example
# Example: Content filtering, virus scanning
ac = AhoCorasick()
# Add forbidden words
words = ["malware", "virus", "trojan", "worm"]
for word in words:
ac.add_pattern(word)
ac.build_failure_function()
# Scan content
content = "This malware contains a virus and trojan code."
matches = ac.search(content)
for match in matches:
print(f"Found '{match['pattern']}' at position {match['start_pos']}")
# Output:
# Found 'malware' at position 5
# Found 'virus' at position 25
# Found 'trojan' at position 38
Visual: Failure Link Flow
"""
When processing character 'e' at "she":
Path to sh: s → h
Need to match next 'e'
1. sh.goto['e'] exists? YES
└─> current = sh_node.goto['e']
If sh.goto['e'] didn't exist:
2. Check sh.fail (→ h).goto['e']?
└─> h.goto['e'] exists! Set current to h_node.goto['e']
If h.goto['e'] didn't exist:
3. Check h.fail (→ root).goto['e']?
└─> If found, go there. Else restart at root.
This guarantees we find the longest match!
"""
Complexity Summary
| Operation | Time | Space |
|---|
| Add m patterns | O(m) | O(m) |
| Build failure links | O(m) | O(m) |
| Scan n characters | O(n) | O(1) |
| Find z matches | O(z) | O(z) |
| Total | O(m+n+z) | O(m) |
The Aho-Corasick algorithm is optimal for multi-pattern matching—you cannot do better than O(m+n+z) since you must read all inputs and output all results.