Algorithm Atlas · worked example
See the algorithm, step by step
Extend one character while cloning states when needed to preserve end-position equivalence classes.
This call is starting. Local values appear as they are initialized.
Data & variables
Changed Source indexExample input
ababaFollow the code. Data appears here when it enters scope.
Call stack · 1 frame
maincall 1
Rust source
Line 61#[derive(Clone)]
struct SuffixState {
length: usize,
link: Option<usize>,
next: std::collections::BTreeMap<u8, usize>,
}
fn distinct_substrings(text: &str) -> usize {
let empty = SuffixState {
length: 0,
link: None,
next: std::collections::BTreeMap::new(),
};
let mut states = vec![empty.clone()];
let mut last = 0;
for c in text.bytes() {
let current = states.len();
states.push(SuffixState {
length: states[last].length + 1,
..empty.clone()
});
let mut p = Some(last);
while let Some(v) = p {
if states[v].next.contains_key(&c) {
break;
}
states[v].next.insert(c, current);
p = states[v].link;
}
if let Some(v) = p {
let q = states[v].next[&c];
if states[v].length + 1 == states[q].length {
states[current].link = Some(q);
} else {
let clone = states.len();
let mut copied = states[q].clone();
copied.length = states[v].length + 1;
states.push(copied);
while let Some(v) = p {
if states[v].next.get(&c) != Some(&q) {
break;
}
states[v].next.insert(c, clone);
p = states[v].link;
}
states[q].link = Some(clone);
states[current].link = Some(clone);
}
} else {
states[current].link = Some(0);
}
last = current;
}
states
.iter()
.skip(1)
.map(|s| s.length - states[s.link.unwrap()].length)
.sum()
}
fn main() {
let result = distinct_substrings("ababa").to_string();
println!("{result}");
}
Try your own version
Compare the visible input `ababa` with `abcde`. Predict why their results are `9` and `15`. Then change one legal value and explain whether the same invariant, it represents one new substring for each length in that interval, 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
For ababa, the automaton represents 9 distinct nonempty substrings. A cloned state splits an existing length class without adding text. For aaa, the length intervals contribute only a,aa,aaa, giving 3 rather than counting repeated occurrences separately.
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: Return the number of distinct non-empty substrings. The visible fixture is ababa and its example result is 9. 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 Suffix Automaton when it asks for all substrings, repeated substring counts, online text indexing. Here the concrete task is: Return the number of distinct non-empty substrings. The visible input ababa is an example, not a definition of the whole problem. Ask what operations the solution must support and what the input guarantees. Choose it when the required operation sequence, query volume, or substring structure exceeds a simple scan or prefix summary; compare the real time and memory limits first. The right choice follows from those guarantees, not from a familiar noun in the prompt.
The decisive invariant is: Extend one character while cloning states when needed to preserve end-position equivalence classes. 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? An advanced structure or offline query order packages an invariant across operations. Name what each node, block, or reordered query state stores. 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(n log alphabet) with ordered transitions · O(n) states and transitions; 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 9 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 ranges, repeated updates, undo operations where supported, and the exact boundary between adjacent blocks. Keep representation and operations separate in Rust. Verify a tiny instance against a straightforward reference implementation before optimizing. 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
Extend one character while cloning states when needed to preserve end-position equivalence classes.
When to use it: all substrings, repeated substring counts, online text indexing
Complexity: O(n log alphabet) with ordered transitions · O(n) states and transitions
Input: ababa
Read the code
#[derive(Clone)]
struct SuffixState {
length: usize,
link: Option<usize>,
next: std::collections::BTreeMap<u8, usize>,
}
fn distinct_substrings(text: &str) -> usize {
let empty = SuffixState {
length: 0,
link: None,
next: std::collections::BTreeMap::new(),
};
let mut states = vec![empty.clone()];
let mut last = 0;
for c in text.bytes() {
let current = states.len();
states.push(SuffixState {
length: states[last].length + 1,
..empty.clone()
});
let mut p = Some(last);
while let Some(v) = p {
if states[v].next.contains_key(&c) {
break;
}
states[v].next.insert(c, current);
p = states[v].link;
}
if let Some(v) = p {
let q = states[v].next[&c];
if states[v].length + 1 == states[q].length {
states[current].link = Some(q);
} else {
let clone = states.len();
let mut copied = states[q].clone();
copied.length = states[v].length + 1;
states.push(copied);
while let Some(v) = p {
if states[v].next.get(&c) != Some(&q) {
break;
}
states[v].next.insert(c, clone);
p = states[v].link;
}
states[q].link = Some(clone);
states[current].link = Some(clone);
}
} else {
states[current].link = Some(0);
}
last = current;
}
states
.iter()
.skip(1)
.map(|s| s.length - states[s.link.unwrap()].length)
.sum()
}
fn main() {
let result = distinct_substrings("ababa").to_string();
println!("{result}");
}
Complete std-only suffix-automaton 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 Suffix Automaton on input a. Which result follows from the documented contract?
Reveal the answer
210
For this input the result is 1. It represents one new substring for each length in that interval. Compare this independent fixture with the worked trace: For ababa, the automaton represents 9 distinct nonempty substrings. A cloned state splits an existing length class without adding text. For aaa, the length intervals contribute only a,aa,aaa, giving 3 rather than counting repeated occurrences separately.
Go deeper
Common misconception: “Every state represents exactly one substring”
It represents one new substring for each length in that interval. For ababa, the automaton represents 9 distinct nonempty substrings. A cloned state splits an existing length class without adding text. For aaa, the length intervals contribute only a,aa,aaa, giving 3 rather than counting repeated occurrences separately.
- Concrete transition: For ababa, the automaton represents 9 distinct nonempty substrings. A cloned state splits an existing length class without adding text. For aaa, the length intervals contribute only a,aa,aaa, giving 3 rather than counting repeated occurrences separately.
- Independent second fixture: Input
aproduces1. 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
abacabaproduces21. It represents one new substring for each length in that interval. The stated work bound is O(n log alphabet) with ordered transitions · O(n) states and transitions. Count actual state changes; a successful output test alone does not prove that bound.
Transfer challenge: Compare the visible input ababa with abcde. Predict why their results are 9 and 15. Then change one legal value and explain whether the same invariant, it represents one new substring for each length in that interval, still applies.
Connections
- Suffix Automaton: Mental Model: Extend one character while cloning states when needed to preserve end-position equivalence classes.
- Challenge: Suffix Automaton: Return the number of distinct non-empty substrings.
Reveal the Algorithm Atlas answer
9
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: Suffix Automaton: When to Use It (courseId "algorithms", lessonId "algorithm.suffix-automaton.recognize") Link: https://crabrix.com/learn/algorithms/algorithm.suffix-automaton.recognize Goal: It represents one new substring for each length in that interval. State the input preconditions before applying this invariant. Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=algorithms/algorithm.suffix-automaton.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.