Tries & String Matching · 15 min · free lesson

Challenge: Suffix Array

Return suffix starting indexes in lexicographic order.

Core idea

Two width-k ranks identify a width-2k comparison key. Return suffix starting indexes in lexicographic order.

Algorithm Atlas · worked example

See the algorithm, step by step

On your device

Sort suffix ranks by doubling compared prefix length until every suffix has a unique rank.

O(n log^2 n) comparison-sort doubling · O(n) auxiliary space33 execution steps
main · before line 30Initialize a local value

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

Data & variables

Changed Source index
Example inputaba

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

Call stack · 1 frame
  1. maincall 1

Rust source

Line 30
fn csv<T: std::fmt::Display>(a: impl IntoIterator<Item = T>) -> String {
    a.into_iter()
        .map(|x| x.to_string())
        .collect::<Vec<_>>()
        .join(",")
}
fn suffix_array(text: &str) -> Vec<usize> {
    let n = text.len();
    let mut order: Vec<_> = (0..n).collect();
    let mut rank: Vec<i32> = text.bytes().map(i32::from).collect();
    let mut width = 1;
    while width < n {
        order.sort_unstable_by_key(|&i| (rank[i], rank.get(i + width).copied().unwrap_or(-1)));
        let mut next = vec![0; n];
        for i in 1..n {
            let (a, b) = (order[i - 1], order[i]);
            let key = |j: usize| (rank[j], rank.get(j + width).copied().unwrap_or(-1));
            next[b] = next[a] + i32::from(key(a) != key(b));
        }
        rank = next;
        if n == 0 || rank[order[n - 1]] == n as i32 - 1 {
            break;
        }
        width *= 2;
    }
    order // comparison-sort doubling: O(n log² n), byte indexes
}
 
fn main() {
    let result = csv(suffix_array("aba"));
    println!("{result}");
}

Try your own version

Change the independent fixture `aba` in a legal way, then compare the result with your prediction. Explain how the same invariant applies to the separate visible challenge `banana`.

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. Borrowed or moved values are hidden when they cannot be inspected safely.
Five-panel Tries & String Matching infographic; panel 4 illustrates Suffix Array.
Suffix Array: follow panel 4 to see the operation, then trace the lesson's own example.

Understand it

Two width-k ranks identify a width-2k comparison key. The worked program demonstrates this invariant on an independent fixture, so you can study the implementation before predicting the challenge result.

For teaching input aba, the worked program returns 2,0,1. Its functions are complete and use only std. Adapt the same state transitions to the visible challenge input banana; predict that result before opening the answer reveal. The precise contract is: Return suffix starting indexes in lexicographic order.

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 suffix starting indexes in lexicographic order. On input banana, 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: Sort suffix ranks by doubling compared prefix length until every suffix has a unique rank. 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(n log^2 n) comparison-sort doubling · O(n) auxiliary space; 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

Sort suffix ranks by doubling compared prefix length until every suffix has a unique rank.

When to use it: substring order, repeated substrings, offline text indexes

Complexity: O(n log^2 n) comparison-sort doubling · O(n) auxiliary space

Input: banana

Read the code

fn csv<T: std::fmt::Display>(a: impl IntoIterator<Item = T>) -> String {
    a.into_iter()
        .map(|x| x.to_string())
        .collect::<Vec<_>>()
        .join(",")
}
fn suffix_array(text: &str) -> Vec<usize> {
    let n = text.len();
    let mut order: Vec<_> = (0..n).collect();
    let mut rank: Vec<i32> = text.bytes().map(i32::from).collect();
    let mut width = 1;
    while width < n {
        order.sort_unstable_by_key(|&i| (rank[i], rank.get(i + width).copied().unwrap_or(-1)));
        let mut next = vec![0; n];
        for i in 1..n {
            let (a, b) = (order[i - 1], order[i]);
            let key = |j: usize| (rank[j], rank.get(j + width).copied().unwrap_or(-1));
            next[b] = next[a] + i32::from(key(a) != key(b));
        }
        rank = next;
        if n == 0 || rank[order[n - 1]] == n as i32 - 1 {
            break;
        }
        width *= 2;
    }
    order // comparison-sort doubling: O(n log² n), byte indexes
}

fn main() {
    let result = csv(suffix_array("aba"));
    println!("{result}");
}

Complete std-only suffix-array 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 suffix starting indexes in lexicographic order.
    // Trim surrounding whitespace; implement parsing and the algorithm.
    let _ = input;
    todo!("implement suffix-array")
}

Try it

Return suffix starting indexes in lexicographic order.

What success looks like: The private harness prints PASS suffix-array. 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-array: with input abacaba, what result should solve return?

Reveal the answer
  1. 6,4,0,2,5,1,3
  2. 4,0,2,5,1,3
  3. 7,4,0,2,5,1,3

For this input the result is 6,4,0,2,5,1,3. Two width-k ranks identify a width-2k comparison key. Compare this independent fixture with the worked trace: For banana, suffix order is a,ana,anana,banana,na,nana at indexes 5,3,1,0,4,2. Rank pairs refine ties each doubling round. This comparison-sort implementation costs O(n log² n), rather than claiming radix-sort bounds it does not implement.

Go deeper

Common misconception: “Doubling removes half of the suffixes”

Two width-k ranks identify a width-2k comparison key. The independent teaching fixture demonstrates this rule; predict the separate visible challenge before revealing its answer.

  1. Pattern-specific invariant: Two width-k ranks identify a width-2k comparison key. 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 aba and computes 2,0,1. Keep parsing separate, then identify the core state before and after this call.
  3. Different legal case: For abacaba, the independently calculated result is 6,4,0,2,5,1,3. The complexity discussion uses O(n log^2 n) comparison-sort doubling · O(n) auxiliary space. Verify the state invariant before reasoning about the operation count.

Transfer challenge: Change the independent fixture aba in a legal way, then compare the result with your prediction. Explain how the same invariant applies to the separate visible challenge banana.

Connections

  • Suffix Array: When to Use It: substring order, repeated substrings, offline text indexes
  • Manacher Palindrome Radii: Mental Model: Mirror known radii inside the rightmost palindrome and expand only beyond its boundary.
Reveal the Algorithm Atlas answer

5,3,1,0,4,2

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 Array (courseId "algorithms", lessonId "algorithm.suffix-array.challenge")
Link: https://crabrix.com/learn/algorithms/algorithm.suffix-array.challenge
Goal: Two width-k ranks identify a width-2k comparison key. Return suffix starting indexes in lexicographic order.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=algorithms/algorithm.suffix-array.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.