Z-Algorithm String Matching
Tutorial Video
Text description (accessibility)
This video demonstrates the "Z-Algorithm String Matching" functional Rust example. Difficulty level: Fundamental. Key concepts covered: Functional Programming. The Z-algorithm computes, for each position in a string, the length of the longest substring starting at that position that is also a prefix of the whole string. Key difference from OCaml: | Aspect | Rust | OCaml |
Tutorial
The Problem
The Z-algorithm computes, for each position in a string, the length of the longest substring starting at that position that is also a prefix of the whole string. This Z-array answers pattern matching questions directly: concatenate pattern + "$" + text, compute the Z-array, and any position where Z[i] equals the pattern length is a match. The algorithm runs in O(n) time and O(n) space, making it a linear alternative to KMP with a simpler conceptual model. It powers prefix-related string queries in competitive programming, bioinformatics repeat analysis, and text compression preprocessing.
🎯 Learning Outcomes
P + $ + T → find positions where Z[i] == |P|Code Example
#![allow(clippy::all)]
//! PlaceholderKey Differences
| Aspect | Rust | OCaml |
|---|---|---|
| Input type | &[u8] — byte slice | bytes or string |
| Z-box state | Two usize variables | int ref or threaded recursion |
| Concatenation | [pattern, b'$', text].concat() | Bytes.concat |
| Bound checks | Debug-mode auto-checks | Bytes.get raises exception |
| Result filter | enumerate().filter() | Array.to_seq \|> Seq.filter_mapi |
| Separator byte | Must not appear in input | Same constraint |
OCaml Approach
OCaml implements the Z-function with mutable int ref for l and r, or threads them through a tail-recursive loop. Bytes.get provides O(1) character access. The Array.make n 0 creates the Z-array. OCaml's pattern matching on the Z-box condition i < r maps cleanly to if i < !r then. For string matching, Bytes.concat Bytes.empty [pattern; sep; text] creates the concatenated input. The result scan Array.to_seq |> Seq.filter_mapi finds positions where Z equals pattern length.
Full Source
#![allow(clippy::all)]
//! PlaceholderDeep Comparison
OCaml vs Rust: Z Algorithm
Overview
See the example.rs and example.ml files for detailed implementations.
Key Differences
| Aspect | OCaml | Rust |
|---|---|---|
| Type system | Hindley-Milner | Ownership + traits |
| Memory | GC | Zero-cost abstractions |
| Mutability | Explicit ref | mut keyword |
| Error handling | Option/Result | Result<T, E> |
See README.md for detailed comparison.
Exercises
s[i..] + s[..i].