Tries & String Matching · 15 min · free lesson

Challenge: Aho–Corasick

Parse lowercase ASCII text and nonempty lowercase ASCII patterns. Count every pattern occurrence, including overlaps and simultaneous suffix matches.

Core idea

A suffix of the current match may itself be a pattern. Parse lowercase ASCII text and nonempty lowercase ASCII patterns. Count every pattern occurrence, including overlaps and simultaneous suffix matches.

Algorithm Atlas · worked example

See the algorithm, step by step

On your device

Add failure links to a trie so one scan reports all pattern suffixes ending at each position.

O(text + matches + total patterns) time302 execution steps
main · before line 57Initialize a local value

This call is starting. Local values appear as they are initialized.

Data & variables

Changed Source index
Example inputtext=aaaa patterns=[a,aa]

Follow the code. Data appears here when it enters scope.

Call stack · 1 frame
  1. 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("aaaa", &["a", "aa"]).to_string();
    println!("{result}");
}

Try your own version

Change the independent fixture `text=aaaa patterns=[a,aa]` in a legal way, then compare the result with your prediction. Explain how the same invariant applies to the separate visible challenge `text=ahishers patterns=[he,she,his,hers]`.

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.

Recorded from this Rust example and checked against its original output. Playback runs locally in your browser. Values show the state before the highlighted line.
Five-panel Tries & String Matching infographic; panel 3 illustrates Aho Corasick.
Aho Corasick: follow panel 3 to see the operation, then trace this lesson's example.

Understand it

A suffix of the current match may itself be a pattern. The worked program demonstrates this invariant on an independent fixture, so you can study the implementation before predicting the challenge result.

For teaching input text=aaaa patterns=[a,aa], the worked program returns 7. Its functions are complete and use only std. Adapt the same state transitions to the visible challenge input text=ahishers patterns=[he,she,his,hers]; predict that result before opening the answer reveal. The precise contract is: Parse lowercase ASCII text and nonempty lowercase ASCII patterns. Count every pattern occurrence, including overlaps and simultaneous suffix matches.

Return canonical output: lowercase booleans, decimal integers without leading zeros, comma-separated values and semicolon-separated groups, with no extra whitespace or final newline. Whole medians use integer form and half medians use .5. Textual sentinels such as none and # retain their stated meaning. String and character-grid fixtures use ASCII unless the lesson explicitly specifies Unicode scalar values.

Solve the exact task, not just the visible example: Parse lowercase ASCII text and nonempty lowercase ASCII patterns. Count every pattern occurrence, including overlaps and simultaneous suffix matches. On input text=ahishers patterns=[he,she,his,hers], predict the output before opening the answer reveal. The revealed output is a test oracle for this case, while private checks exercise other legal cases. Start by stating the input grammar and output format in your own words. Parse the complete input, including surrounding whitespace, before relying on any convenient positions in the example.

Build the solution around one maintained claim: Add failure links to a trie so one scan reports all pattern suffixes ending at each position. Decide what state represents that claim, how it is initialized, what a single update does, and when the algorithm stops. 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. Trace the visible input by hand and record at least two intermediate states, not only the final answer. If the trace cannot justify your predicted output, there is a gap between the idea and the implementation.

Check both correctness and cost. The intended bound is O(text + matches + total patterns) time; explain which operation dominates it and how many times the input can trigger that operation. Test empty pattern and text, repeated characters, overlapping matches, and non-ASCII input if the contract allows it. Add one small case that should succeed, one boundary case, and one case chosen to challenge the invariant. Compare your hand result with the program's result, then use a failing case to fix the earliest incorrect state transition rather than patching the final output.

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("aaaa", &["a", "aa"]).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.

Practice starter

pub fn solve(input: &str) -> String {
    // Parse lowercase ASCII text and nonempty lowercase ASCII patterns. Count every pattern occurrence, including overlaps and simultaneous suffix matches.
    // Trim surrounding whitespace; implement parsing and the algorithm.
    let _ = input;
    todo!("implement aho-corasick")
}

Try it

Parse lowercase ASCII text and nonempty lowercase ASCII patterns. Count every pattern occurrence, including overlaps and simultaneous suffix matches.

What success looks like: The private harness prints PASS aho-corasick. It checks at least five distinct semantic inputs plus surrounding-whitespace variants. Explain complexity separately; this harness does not time the algorithm.

Check your understanding

Boundary check for aho-corasick: with input text=she patterns=[s,he,she], what result should solve return?

Reveal the answer
  1. 3
  2. 4
  3. 2

For this input the result is 3. 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. The independent teaching fixture demonstrates this rule; predict the separate visible challenge before revealing its answer.

  1. Pattern-specific invariant: A suffix of the current match may itself be a pattern. This is the property the named implementation maintains; explain which comparison, state update or recursive return in the worked program establishes it.
  2. Independent typed fixture: The worked call uses text=aaaa patterns=[a,aa] and computes 7. Keep parsing separate, then identify the core state before and after this call.
  3. Different legal case: For text=she patterns=[s,he,she], the independently calculated result is 3. The complexity discussion uses O(text + matches + total patterns) time. Verify the state invariant before reasoning about the operation count.

Transfer challenge: Change the independent fixture text=aaaa patterns=[a,aa] in a legal way, then compare the result with your prediction. Explain how the same invariant applies to the separate visible challenge text=ahishers patterns=[he,she,his,hers].

Connections

  • Aho–Corasick: When to Use It: many-pattern search, filters, signature scanning
  • Suffix Array: Mental Model: Sort suffix ranks by doubling compared prefix length until every suffix has a unique rank.
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: Challenge: Aho–Corasick (courseId "algorithms", lessonId "algorithm.aho-corasick.challenge")
Link: https://crabrix.com/learn/algorithms/algorithm.aho-corasick.challenge
Goal: A suffix of the current match may itself be a pattern. Parse lowercase ASCII text and nonempty lowercase ASCII patterns. Count every pattern occurrence, including overlaps and simultaneous suffix matches.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=algorithms/algorithm.aho-corasick.challenge) 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.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.