1. Z array
z[i] is the length of the longest substring at i matching the prefix.
const z = new Array(n).fill(0)Typorithm · hard
Step 1 of 8 · intro card
String Algorithms
Compute z[i], the longest prefix match starting at i, reusing a [left, right] z-box to stay linear.
The Z-array gives, for each index, how far the substring there matches the string's own prefix.
A maintained [left, right] window (the z-box) lets earlier results be reused instead of recomputed.
Combined with extend-and-update, the whole array is built in O(n).
z[i] = prefix match length at i.
Reuse z inside the [left, right] box.
Extend, then update the box.
function zFunction(s) {
const n = s.length;
const z = new Array(n).fill(0);
let left = 0;
let right = 0;
for (let i = 1; i < n; i += 1) {
if (i < right) {
z[i] = Math.min(right - i, z[i - left]);
}
while (i + z[i] < n && s[z[i]] === s[i + z[i]]) {
z[i] += 1;
}
if (i + z[i] > right) {
left = i;
right = i + z[i];
}
}
return z;
}Connect each part of the code to the concept before you type.
z[i] is the length of the longest substring at i matching the prefix.
const z = new Array(n).fill(0)Inside the current [left, right] box, reuse a previously computed z value.
z[i] = Math.min(right - i, z[i - left])Grow the match by comparing prefix characters directly.
while (i + z[i] < n && s[z[i]] === s[i + z[i]])If the match reaches further, move the [left, right] box forward.
if (i + z[i] > right)Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
InputString aabcaab · Z[i] = length matching prefix
Follow temporary values, local state and supporting structures at this step.
↗ The 7-cell working table above is itself auxiliary memory. Input values are shown separately.
Input · not auxiliary memory
Characters7 entries
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state