Algorithm Atlas · worked example
See the algorithm, step by step
Add failure links to a trie so one scan reports all pattern suffixes ending at each position.
This call is starting. Local values appear as they are initialized.
Data & variables
Changed Source indexExample input
text=ahishers patterns=[he,she,his,hers]Follow the code. Data appears here when it enters scope.
Call stack · 1 frame
maincall 1
Rust source
Line 57#[derive(Clone)]
struct AutomatonNode {
next: [usize; 26],
failure: usize,
matches: usize,
}
fn multi_pattern_count(text: &str, patterns: &[&str]) -> usize {
let empty = AutomatonNode {
next: [0; 26],
failure: 0,
matches: 0,
};
let mut nodes = vec![empty.clone()];
for pattern in patterns {
assert!(!pattern.is_empty());
let mut v = 0;
for c in pattern.bytes() {
assert!(c.is_ascii_lowercase());
let key = (c - b'a') as usize;
if nodes[v].next[key] == 0 {
nodes[v].next[key] = nodes.len();
nodes.push(empty.clone());
}
v = nodes[v].next[key];
}
nodes[v].matches += 1;
}
let mut queue = std::collections::VecDeque::new();
for &u in &nodes[0].next {
if u != 0 {
queue.push_back(u);
}
}
while let Some(v) = queue.pop_front() {
let failure = nodes[v].failure;
nodes[v].matches += nodes[failure].matches;
for c in 0..26 {
let u = nodes[v].next[c];
if u == 0 {
nodes[v].next[c] = nodes[failure].next[c];
} else {
nodes[u].failure = nodes[failure].next[c];
queue.push_back(u);
}
}
}
let (mut state, mut count) = (0, 0);
for c in text.bytes() {
assert!(c.is_ascii_lowercase());
state = nodes[state].next[(c - b'a') as usize];
count += nodes[state].matches;
}
count
}
fn main() {
let result = multi_pattern_count("ahishers", &["he", "she", "his", "hers"]).to_string();
println!("{result}");
}
Try your own version
Compare the visible input `text=ahishers patterns=[he,she,his,hers]` with `text=ababa patterns=[aba,ba]`. Predict why their results are `4` and `4`. Then change one legal value and explain whether the same invariant, a suffix of the current match may itself be a pattern, still applies.
Open personal copy in Playground ↗Start with this exact source and input, change a value, then use Run or Debug locally. This replay stays attached to the original example.
Recordings use a native Rust target. Playground runs on wasm32-wasip1; target-sized types such as usize can have different limits.

Understand it
In ahishers, matches are his, she, he and hers, total 4. At the end of she, its failure chain also recognizes he. In aaaa with patterns a and aa, overlaps produce 4+3=7 matches.
The worked program is a complete executable for this pattern. Its core function uses typed input so the state transitions remain visible. The challenge input contract is: Parse lowercase ASCII text and nonempty lowercase ASCII patterns. Count every pattern occurrence, including overlaps and simultaneous suffix matches. The visible fixture is text=ahishers patterns=[he,she,his,hers] and its example result is 4. The implementation and additional semantic fixtures were checked against an independent reference calculation. Those bounded tests establish these examples; they are not a proof for all inputs or a measurement on an iPhone.
Return a canonical String from solve: lowercase true/false for booleans; decimal integers without extra signs, leading zeros or whitespace; comma-separated sequence values and semicolon-separated groups. Whole-number medians have no decimal suffix; half medians use .5. Do not append a newline to the returned value. Preserve the explicitly named textual sentinels such as none or #. Input fixtures are bounded so the demonstrated arithmetic fits its named Rust types; satisfy the stated input preconditions before applying the algorithm.
String and character-grid fixtures use ASCII unless the lesson explicitly specifies Unicode scalar values.
A problem is a good match for Aho–Corasick when it asks for many-pattern search, filters, signature scanning. Here the concrete task is: Parse lowercase ASCII text and nonempty lowercase ASCII patterns. Count every pattern occurrence, including overlaps and simultaneous suffix matches. The visible input text=ahishers patterns=[he,she,his,hers] is an example, not a definition of the whole problem. Ask what operations the solution must support and what the input guarantees. Look for repeated prefix queries or pattern matching before choosing a trie or preprocessing; a one-off short search may not need either. The right choice follows from those guarantees, not from a familiar noun in the prompt.
The decisive invariant is: Add failure links to a trie so one scan reports all pattern suffixes ending at each position. Try to say why it applies to the task without quoting the implementation. Which fact becomes known after one update, and which possible answers remain? String algorithms compare symbols or prefixes, but a Rust String is UTF-8 bytes. State whether the task means bytes, scalar values, or grapheme clusters. If that claim cannot be maintained on a legal input, the pattern is wrong or one of its preconditions is missing. A counterexample is more useful than a vague warning: change one property of the sample, trace the first two steps, and identify the exact claim that fails.
Compare costs before committing. The advertised bound is O(text + matches + total patterns) time; identify the operation responsible for it and the extra memory it needs. Then compare a straightforward alternative: a direct scan, full sort, or repeated recomputation may be easier but can pay for the same work many times. Do not choose the more elaborate method just because it has a famous name. For the sample, predict 4 and explain which part of the state lets the method reach that result.
When the prompt is ambiguous, ask about input size, ordering, duplicates, and required output format. Test empty pattern and text, repeated characters, overlapping matches, and non-ASCII input if the contract allows it. Use bytes only when the input contract permits byte-wise matching. Never index a String as though every character occupied one byte. The Rust sketch can show a useful primitive without proving that the whole task is solved; connect each primitive to the requested output. You should be able to name a fitting case, a near miss, and the assumption separating them before writing the first line.
The pattern
Add failure links to a trie so one scan reports all pattern suffixes ending at each position.
When to use it: many-pattern search, filters, signature scanning
Complexity: O(text + matches + total patterns) time
Input: text=ahishers patterns=[he,she,his,hers]
Read the code
#[derive(Clone)]
struct AutomatonNode {
next: [usize; 26],
failure: usize,
matches: usize,
}
fn multi_pattern_count(text: &str, patterns: &[&str]) -> usize {
let empty = AutomatonNode {
next: [0; 26],
failure: 0,
matches: 0,
};
let mut nodes = vec![empty.clone()];
for pattern in patterns {
assert!(!pattern.is_empty());
let mut v = 0;
for c in pattern.bytes() {
assert!(c.is_ascii_lowercase());
let key = (c - b'a') as usize;
if nodes[v].next[key] == 0 {
nodes[v].next[key] = nodes.len();
nodes.push(empty.clone());
}
v = nodes[v].next[key];
}
nodes[v].matches += 1;
}
let mut queue = std::collections::VecDeque::new();
for &u in &nodes[0].next {
if u != 0 {
queue.push_back(u);
}
}
while let Some(v) = queue.pop_front() {
let failure = nodes[v].failure;
nodes[v].matches += nodes[failure].matches;
for c in 0..26 {
let u = nodes[v].next[c];
if u == 0 {
nodes[v].next[c] = nodes[failure].next[c];
} else {
nodes[u].failure = nodes[failure].next[c];
queue.push_back(u);
}
}
}
let (mut state, mut count) = (0, 0);
for c in text.bytes() {
assert!(c.is_ascii_lowercase());
state = nodes[state].next[(c - b'a') as usize];
count += nodes[state].matches;
}
count
}
fn main() {
let result = multi_pattern_count("ahishers", &["he", "she", "his", "hers"]).to_string();
println!("{result}");
}
Complete std-only aho-corasick program for its typed teaching fixture. Parsing and output construction are separate from the core algorithm.
Try it
Compare the visible and independent fixtures. Explain the input assumption that makes this algorithm applicable, then identify a change that would invalidate it.
What success looks like: You can justify the choice from constraints rather than from a remembered problem title.
Check your understanding
Trace Aho–Corasick on input text=abc patterns=[x,y]. Which result follows from the documented contract?
Reveal the answer
10-1
For this input the result is 0. A suffix of the current match may itself be a pattern. Compare this independent fixture with the worked trace: In ahishers, matches are his, she, he and hers, total 4. At the end of she, its failure chain also recognizes he. In aaaa with patterns a and aa, overlaps produce 4+3=7 matches.
Go deeper
Common misconception: “Failure links represent unrelated future text”
A suffix of the current match may itself be a pattern. In ahishers, matches are his, she, he and hers, total 4. At the end of she, its failure chain also recognizes he. In aaaa with patterns a and aa, overlaps produce 4+3=7 matches.
- Concrete transition: In ahishers, matches are his, she, he and hers, total 4. At the end of she, its failure chain also recognizes he. In aaaa with patterns a and aa, overlaps produce 4+3=7 matches.
- Independent second fixture: Input
text=abc patterns=[x,y]produces0. Execute the named function in the worked program with these typed arguments, then compare its actual result with this independently computed expectation. - Boundary and contract: Input
text=she patterns=[s,he,she]produces3. A suffix of the current match may itself be a pattern. The stated work bound is O(text + matches + total patterns) time. Count actual state changes; a successful output test alone does not prove that bound.
Transfer challenge: Compare the visible input text=ahishers patterns=[he,she,his,hers] with text=ababa patterns=[aba,ba]. Predict why their results are 4 and 4. Then change one legal value and explain whether the same invariant, a suffix of the current match may itself be a pattern, still applies.
Connections
- Aho–Corasick: Mental Model: Add failure links to a trie so one scan reports all pattern suffixes ending at each position.
- Challenge: Aho–Corasick: Parse lowercase ASCII text and nonempty lowercase ASCII patterns. Count every pattern occurrence, including overlaps and simultaneous suffix matches.
Reveal the Algorithm Atlas answer
4
Learn this lesson with AI
Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.
I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools. Lesson: Aho–Corasick: When to Use It (courseId "algorithms", lessonId "algorithm.aho-corasick.recognize") Link: https://crabrix.com/learn/algorithms/algorithm.aho-corasick.recognize Goal: A suffix of the current match may itself be a pattern. State the input preconditions before applying this invariant. Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=algorithms/algorithm.aho-corasick.recognize) and I will write the code there. Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.