Z algorithm
Intermediate · 10 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
The Z algorithm builds a list that says, for every position in a text, how many letters starting there are identical to the beginning of the text. It reuses what it already learned inside a matched stretch, so the whole list is built in a single quick pass.
Practical use cases
- Web app: Find a keyword in a transcript. A video site shows searchable transcripts. Join the keyword, a separator character, and the transcript into one string, then compute the Z list. Every position whose value equals the keyword length is a place where the keyword starts, so all hits and their timestamps come out of one pass.
- Web app: Detect a repeated token in a serial code. A coupon generator should never produce codes made of a repeating block like "AB12AB12AB12". The Z list immediately shows whether the code is just a smaller block repeated. Checking one code takes a single pass, so you can validate millions of generated codes in a background job.
- System: Analysing repetitive sequences. Tools that look at long sequences, such as genetic data or machine-generated logs, want to know where a segment starts echoing the beginning of the sequence. The Z list gives that for every position in one sweep, and the same trick supports other tasks like comparing two sequences by joining them.
The story: The Echo in the Valley
Mira and Kabir stood at the edge of a valley and shouted "AABXAAB". Back came an echo that repeated the beginning of their shout at several places. Kabir asked, "At each spot in my shout, how much of the very start is being echoed from there?"
They wrote numbers down by hand. At position 1 the echo was "A" (1 letter). At position 4 it was "AAB" (3 letters). At position 5 only "A". The slow way was to compare from scratch at each spot, but Mira noticed something: once she had found that positions 4 to 6 echo the start, positions inside that box could borrow the answers already written for the beginning, with almost no new comparing.
That list of echo lengths is the Z array, and the clever reuse is the Z algorithm. It keeps one box (a "Z-box") around the furthest match so far and reuses it. To search for a pattern in a text, glue them together with a special separator, like pattern#text, and look for any spot whose Z equals the pattern length. Same job as KMP, a different road to it.
How to spot this problem, and where you need it
You want to know, at every position of a string, how much of it repeats the start of the string, or to find a pattern in a text without a separate lookup table.
Signs you need it
- The problem asks for the longest common beginning between a string and each of its tails.
- You are checking whether a string is built from repeating blocks, or finding the smallest block length.
- You are searching for a pattern and want a simple method you can write in a dozen lines without a failure table.
Where to use it in a project
- Keyword search inside transcripts, product descriptions or notes by joining pattern and text.
- Validating generated codes or tokens that must not be a simple repetition.
- Spotting repeating blocks in logs or sequence data in a batch job.
The solution
Walk left to right keeping a box that marks the furthest stretch already known to copy the beginning. For a new position inside the box, start from the answer you already know from the matching earlier spot instead of comparing again. Only extend letter by letter when you reach beyond the box. Every letter is compared very few times, so the whole list appears in one pass.
Payoff: Before: comparing every tail with the start meant up to millions of checks for a 2,000-character string. After: about 2,000.
Explain it like I am 8
Shout a sentence in a valley. At each spot, ask: "from here on, does what I hear sound like the start of my sentence? For how many letters?" Write that number down. If you already know a stretch is an echo of the start, you can reuse old answers inside it.
How it works, step by step
- For each position i from 1 on, compute Z[i] = how many letters from i match the string's beginning.
- Keep a box [l, r): the stretch that matched the beginning and reaches furthest right so far.
- If i is inside the box, start with a free head start: the smaller of
r - iandZ[i - l]. - Keep extending the match one letter at a time while letters agree.
- Update the box if the new match reaches further than r.
- To search, build
pattern + "#" + textand report each spot where Z equals the pattern length.
The code in four languages
PHP
<?php
// Z array: z[i] = how many letters starting at i match the start of the string.
function zArray(string $s): array {
$n = strlen($s);
$z = array_fill(0, $n, 0);
$l = 0;
$r = 0; // box [l, r): furthest match so far
for ($i = 1; $i < $n; $i++) {
$k = 0;
if ($i < $r) {
$k = min($r - $i, $z[$i - $l]); // head start from the box
}
while ($i + $k < $n && $s[$k] === $s[$i + $k]) {
$k++; // extend letter by letter
}
$z[$i] = $k;
if ($i + $k > $r) {
$l = $i;
$r = $i + $k; // new furthest box
}
}
$z[0] = $n;
return $z;
}
// Pattern search: glue pattern # text and look for Z equal to pattern length.
function zSearch(string $text, string $pattern): array {
$m = strlen($pattern);
$z = zArray($pattern . '#' . $text);
$found = [];
for ($i = $m + 1; $i < count($z); $i++) {
if ($z[$i] === $m) {
$found[] = $i - $m - 1; // position inside the text
}
}
return $found;
}
echo implode(' ', zArray("AABXAAB")) . "\n"; // 7 1 0 0 3 1 0
echo json_encode(zSearch("XABABAB", "ABAB")) . "\n"; // [1,3]JavaScript
// Z array: z[i] = how many letters starting at i match the start of the string.
function zArray(s) {
const n = s.length;
const z = new Array(n).fill(0);
let l = 0;
let r = 0; // box [l, r): furthest match so far
for (let i = 1; i < n; i++) {
let k = 0;
if (i < r) {
k = Math.min(r - i, z[i - l]); // head start from the box
}
while (i + k < n && s[k] === s[i + k]) {
k++; // extend letter by letter
}
z[i] = k;
if (i + k > r) {
l = i;
r = i + k; // new furthest box
}
}
z[0] = n;
return z;
}
// Pattern search: glue pattern # text and look for Z equal to pattern length.
function zSearch(text, pattern) {
const m = pattern.length;
const z = zArray(pattern + '#' + text);
const found = [];
for (let i = m + 1; i < z.length; i++) {
if (z[i] === m) {
found.push(i - m - 1); // position inside the text
}
}
return found;
}
console.log(zArray('AABXAAB').join(' ')); // 7 1 0 0 3 1 0
console.log(JSON.stringify(zSearch('XABABAB', 'ABAB'))); // [1,3]Java
import java.util.*;
public class Main {
// Z array: z[i] = how many letters starting at i match the start of the string.
static int[] zArray(String s) {
int n = s.length();
int[] z = new int[n];
int l = 0;
int r = 0; // box [l, r): furthest match so far
for (int i = 1; i < n; i++) {
int k = 0;
if (i < r) {
k = Math.min(r - i, z[i - l]); // head start from the box
}
while (i + k < n && s.charAt(k) == s.charAt(i + k)) {
k++; // extend letter by letter
}
z[i] = k;
if (i + k > r) {
l = i;
r = i + k; // new furthest box
}
}
z[0] = n;
return z;
}
// Pattern search: glue pattern # text and look for Z equal to pattern length.
static List<Integer> zSearch(String text, String pattern) {
int m = pattern.length();
int[] z = zArray(pattern + "#" + text);
List<Integer> found = new ArrayList<>();
for (int i = m + 1; i < z.length; i++) {
if (z[i] == m) {
found.add(i - m - 1); // position inside the text
}
}
return found;
}
public static void main(String[] args) {
System.out.println(Arrays.toString(zArray("AABXAAB"))); // [7, 1, 0, 0, 3, 1, 0]
System.out.println(zSearch("XABABAB", "ABAB")); // [1, 3]
}
}Go
package main
import "fmt"
// zArray returns z where z[i] = how many letters starting at i match the
// start of the string.
func zArray(s string) []int {
n := len(s)
z := make([]int, n)
l, r := 0, 0 // box [l, r): furthest match so far
for i := 1; i < n; i++ {
k := 0
if i < r {
k = min(r-i, z[i-l]) // head start from the box
}
for i+k < n && s[k] == s[i+k] {
k++ // extend letter by letter
}
z[i] = k
if i+k > r {
l = i
r = i + k // new furthest box
}
}
z[0] = n
return z
}
// zSearch glues pattern # text and looks for Z equal to the pattern length.
func zSearch(text, pattern string) []int {
m := len(pattern)
z := zArray(pattern + "#" + text)
var found []int
for i := m + 1; i < len(z); i++ {
if z[i] == m {
found = append(found, i-m-1) // position inside the text
}
}
return found
}
func main() {
fmt.Println(zArray("AABXAAB")) // [7 1 0 0 3 1 0]
fmt.Println(zSearch("XABABAB", "ABAB")) // [1 3]
}Time: O(n) · Extra space: O(n). The box only moves right and every extension step pushes it further, so each letter is compared a few times in total, not once per position.
Watch out for
- Forgetting the separator in
pattern#text. Without it a match could run across the join and Z could exceed the pattern length. - Using a separator letter that also occurs in the pattern or text. Pick a symbol that cannot appear in either.
- Mixing up Z[0]. Most people define it as the whole length, or ignore it; just stay consistent.
Quick check
- For "AABXAAB", what is Z at position 4?
- 1
- 3
- 4
- Why is the Z-box useful?
- It lets us reuse earlier answers inside it
- It sorts the letters
- It stores the pattern
- To find "AB" in "XABAB" with the Z algorithm, you build…
- XABAB#XABAB
- ABXABAB
- AB#XABAB