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
aaaFollow 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("aaa").to_string();
println!("{result}");
}
Try your own version
Change the independent fixture `aaa` in a legal way, then compare the result with your prediction. Explain how the same invariant applies to the separate visible challenge `ababa`.
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
It represents one new substring for each length in that interval. The worked program demonstrates this invariant on an independent fixture, so you can study the implementation before predicting the challenge result.
For teaching input aaa, the worked program returns 3. Its functions are complete and use only std. Adapt the same state transitions to the visible challenge input ababa; predict that result before opening the answer reveal. The precise contract is: Return the number of distinct non-empty substrings.
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: Return the number of distinct non-empty substrings. On input ababa, 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: Extend one character while cloning states when needed to preserve end-position equivalence classes. Decide what state represents that claim, how it is initialized, what a single update does, and when the algorithm stops. An advanced structure or offline query order packages an invariant across operations. Name what each node, block, or reordered query state stores. 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(n log alphabet) with ordered transitions · O(n) states and transitions; explain which operation dominates it and how many times the input can trigger that operation. Test empty ranges, repeated updates, undo operations where supported, and the exact boundary between adjacent blocks. 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
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("aaa").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.
Practice starter
pub fn solve(input: &str) -> String {
// Return the number of distinct non-empty substrings.
// Trim surrounding whitespace; implement parsing and the algorithm.
let _ = input;
todo!("implement suffix-automaton")
}
Try it
Return the number of distinct non-empty substrings.
What success looks like: The private harness prints PASS suffix-automaton. 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 suffix-automaton: with input abacaba, what result should solve return?
Reveal the answer
212220
For this input the result is 21. 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. The independent teaching fixture demonstrates this rule; predict the separate visible challenge before revealing its answer.
- Pattern-specific invariant: It represents one new substring for each length in that interval. This is the property the named implementation maintains; explain which comparison, state update or recursive return in the worked program establishes it.
- Independent typed fixture: The worked call uses
aaaand computes3. Keep parsing separate, then identify the core state before and after this call. - Different legal case: For
abacaba, the independently calculated result is21. The complexity discussion uses O(n log alphabet) with ordered transitions · O(n) states and transitions. Verify the state invariant before reasoning about the operation count.
Transfer challenge: Change the independent fixture aaa in a legal way, then compare the result with your prediction. Explain how the same invariant applies to the separate visible challenge ababa.
Connections
- Suffix Automaton: When to Use It: all substrings, repeated substring counts, online text indexing
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: Challenge: Suffix Automaton (courseId "algorithms", lessonId "algorithm.suffix-automaton.challenge") Link: https://crabrix.com/learn/algorithms/algorithm.suffix-automaton.challenge Goal: It represents one new substring for each length in that interval. Return the number of distinct non-empty substrings. Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=algorithms/algorithm.suffix-automaton.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.