The Z-algorithm #
The Z-function of a word s records, at each position i, the length of the longest common
prefix of s and its suffix s.drop i. The Z-algorithm ([Gusfield1997], Section 1.4) computes
all of these values from left to right. It keeps the box [l, r), the rightmost interval found
so far that repeats a prefix of s. At a position i inside the box, the value z[i - l]
either gives z[i] outright or shows that z[i] ≥ r - i, so explicit comparisons start at
r.
Machine-level O(|s|) and O(|p| + |t|) running-time bounds on word arrays are proved in
CslibFrontier.Algorithms.WordRAM.ZFunction.
Source Conventions #
- Indexing: positions are
0-based, andz[0] = |s|(the whole word is a prefix of itself). Gusfield indexes from1and leavesZ_1undefined. - Box:
[l, r)is half-open. Gusfield's box[l, r]is closed and1-indexed. Initiallyl = r = 0, the empty box.
Main definitions #
Cslib.Algorithms.Lean.ZFunction.zFunction: the specificationz[i] = List.lcpLen s (s.drop i).Cslib.Algorithms.Lean.ZFunction.zArray,zAlgorithm: the pure Z-algorithm on arrays and its list wrapper.
Main results #
Cslib.Algorithms.Lean.ZFunction.min_lcpLen_zBox: inside a valid Z-box[l, r),s.drop (i - l)ands.drop ihave the same longest common prefix withsup tor - i.Cslib.Algorithms.Lean.ZFunction.zArray_toList,size_zArray,getElem_zArray,getD_zArray, andzAlgorithm_eq_zFunction: the computed table agrees with the Z-function.
References #
Specification #
The Z-function of s: at each position i < |s|, the length of the longest common prefix
of s and s.drop i.
The algorithm #
The pure Z-algorithm on arrays. The value at 0 is the length of the word; the loop computes
the remaining positions from left to right.
The Z-algorithm on lists.
Correctness #
Z-box transfer lemma ([Gusfield1997], Section 1.4): if [l, r) repeats a prefix of s
(r ≤ l + List.lcpLen s (s.drop l)) and l ≤ i ≤ r, then s.drop (i - l) and s.drop i agree on
their longest common prefix with s up to r - i.
Reading the Z table with default zero gives the common prefix length at every position. At and beyond the end of the array the remaining suffix is empty.
Correctness of the Z-algorithm on lists.