AlgoTales · Roadmap

Z algorithm

Advanced · 11 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

The Z algorithm computes, for every position of a string, how many letters from there match the very start of the string. Gluing a pattern in front of a text turns this into an exact search that reads the text in one pass.

Practical use cases

  • Web app: Find every occurrence of a word in a document. An online editor highlights all matches of a typed phrase in a long document. By computing match lengths against the phrase in one sweep, it finds every position in a single pass, so highlighting stays smooth as the document grows.
  • Web app: Detecting repeated patterns in data. A data-quality tool checks whether a long code or text field is made of a repeating chunk, such as "ABCABCABC". The match lengths show immediately where the string starts echoing itself. The tool can then warn that a field looks suspicious, using one quick pass instead of many comparisons of prefixes.
  • System: Bio-informatics and contests. Gene analysis and contest problems that ask for repeats or borders in strings use this because the code is short and always runs in a single pass.

The story: Mira and the Echo Valley

On a school trip to the hills, Mira shouted a word into Echo Valley and counted how much of her word came back. For some words the echo repeated her whole opening; for others it repeated just a letter or two. Mrs. Sharma asked the class a puzzle: "At every position of a long word, how many letters match the word's own beginning?"

Kabir tried it the slow way: stand at position 5, compare with the start, count; stand at position 6, compare again... He kept repeating work. Mira noticed that once you find a long echo, say from position 4 to 6, you hold a box where the word looks exactly like its beginning. Standing inside the box, the answer for a nearby position is already written in the early part of the word!

So she kept a little box [l, r] of the farthest echo so far. Inside the box, copy an old answer (trim it if it pokes out of the box). Only at the box edge do you compare new letters, and that stretches the box. That is the Z algorithm: all answers in one pass, and a fast way to search by gluing a pattern in front of a text.

How to spot this problem, and where you need it

You need to find where a pattern occurs, or where a string repeats itself, and repeated rescanning makes the code slow on large input.

Signs you need it

  • The problem asks for all positions where a pattern appears, or whether a string is built from repeats.
  • You compare prefixes of the string with its later parts, again and again.
  • Naive nested loops are fine for short strings but slow on long ones.
  • The words "prefix", "border" or "period" appear in the problem.

Where to use it in a project

  • Highlight-all-matches features in code editors and online document viewers.
  • Validators that detect repeating patterns in codes, sequences or data columns.

The solution

For each position i, compute Z[i], the number of letters starting at i that equal the start of the string. Keep a window [L, R] covering the furthest match found; inside this window, copy earlier answers instead of recounting, and extend only beyond it. For search, join pattern + a separator + text; positions with Z equal to the pattern length are matches.

Payoff: Before: rescanning from each position, which grows quickly with length. After: a single left-to-right pass over the combined string.

Explain it like I am 8

Imagine a word shouting back at itself: at every spot you ask "how much of my beginning do I repeat from here?" A smart kid keeps a ruler box over the longest echo found so far, and inside it just copies old answers instead of measuring again.

How it works, step by step

  1. Make an array z. z[i] is how many letters from position i equal the start of the word.
  2. Keep a box [l, r): the farthest-reaching echo found so far (start empty).
  3. At position i: if it is inside the box, start with min(r - i, z[i - l]), a free head start copied from earlier.
  4. Then keep comparing letters while they match, and bump z[i] each time.
  5. If this echo reaches farther than r, move the box to [i, i + z[i]).
  6. To search, build pattern + "#" + text; every position whose z equals the pattern length is a match.

The code in four languages

PHP

<?php
// z[i] = length of the longest match between s[i..] and the start of s.
function zArray(string $s): array {
    $n = strlen($s);
    $z = array_fill(0, $n, 0);
    $z[0] = $n;
    $l = 0; $r = 0;                                    // box [l, r)
    for ($i = 1; $i < $n; $i++) {
        if ($i < $r) $z[$i] = min($r - $i, $z[$i - $l]);   // free head start
        while ($i + $z[$i] < $n && $s[$z[$i]] === $s[$i + $z[$i]]) $z[$i]++;
        if ($i + $z[$i] > $r) { $l = $i; $r = $i + $z[$i]; }
    }
    return $z;
}
// Search: glue pattern # text, and look for z == pattern length.
function zSearch(string $text, string $pat): array {
    $m = strlen($pat);
    $z = zArray($pat . "#" . $text);
    $res = [];
    for ($i = $m + 1; $i < count($z); $i++) {
        if ($z[$i] === $m) $res[] = $i - $m - 1;
    }
    return $res;
}
echo implode(",", zArray("aabcaabxaab")), "\n";       // 11,1,0,0,3,1,0,0,3,1,0
echo implode(",", zSearch("abracadabra", "abra")), "\n";   // 0,7

JavaScript

// z[i] = length of the longest match between s[i..] and the start of s.
function zArray(s) {
  const n = s.length;
  const z = new Array(n).fill(0);
  z[0] = n;
  let l = 0, r = 0;                                  // box [l, r)
  for (let i = 1; i < n; i++) {
    if (i < r) z[i] = Math.min(r - i, z[i - l]);     // free head start
    while (i + z[i] < n && s[z[i]] === s[i + z[i]]) z[i]++;
    if (i + z[i] > r) { l = i; r = i + z[i]; }
  }
  return z;
}
// Search: glue pattern # text, and look for z == pattern length.
function zSearch(text, pat) {
  const m = pat.length;
  const z = zArray(pat + "#" + text);
  const res = [];
  for (let i = m + 1; i < z.length; i++) {
    if (z[i] === m) res.push(i - m - 1);
  }
  return res;
}
console.log(zArray("aabcaabxaab").join(","));        // 11,1,0,0,3,1,0,0,3,1,0
console.log(zSearch("abracadabra", "abra").join(","));   // 0,7

Java

import java.util.*;

public class Main {
    // z[i] = length of the longest match between s[i..] and the start of s.
    static int[] zArray(String s) {
        int n = s.length();
        int[] z = new int[n];
        z[0] = n;
        int l = 0, r = 0;                                  // box [l, r)
        for (int i = 1; i < n; i++) {
            if (i < r) z[i] = Math.min(r - i, z[i - l]);   // free head start
            while (i + z[i] < n && s.charAt(z[i]) == s.charAt(i + z[i])) z[i]++;
            if (i + z[i] > r) { l = i; r = i + z[i]; }
        }
        return z;
    }

    // Search: glue pattern # text, and look for z == pattern length.
    static List<Integer> zSearch(String text, String pat) {
        int m = pat.length();
        int[] z = zArray(pat + "#" + text);
        List<Integer> res = new ArrayList<>();
        for (int i = m + 1; i < z.length; i++) {
            if (z[i] == m) res.add(i - m - 1);
        }
        return res;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(zArray("aabcaabxaab")));       // [11, 1, 0, 0, 3, 1, 0, 0, 3, 1, 0]
        System.out.println(zSearch("abracadabra", "abra"));               // [0, 7]
    }
}

Go

package main

import "fmt"

// zArray: z[i] = length of the longest match between s[i..] and the start of s.
func zArray(s string) []int {
	n := len(s)
	z := make([]int, n)
	z[0] = n
	l, r := 0, 0 // box [l, r)
	for i := 1; i < n; i++ {
		if i < r {
			z[i] = min(r-i, z[i-l]) // free head start
		}
		for i+z[i] < n && s[z[i]] == s[i+z[i]] {
			z[i]++
		}
		if i+z[i] > r {
			l, r = i, i+z[i]
		}
	}
	return z
}

// zSearch glues pattern # text, and looks for z == pattern length.
func zSearch(text, pat string) []int {
	m := len(pat)
	z := zArray(pat + "#" + text)
	var res []int
	for i := m + 1; i < len(z); i++ {
		if z[i] == m {
			res = append(res, i-m-1)
		}
	}
	return res
}

func main() {
	fmt.Println(zArray("aabcaabxaab"))          // [11 1 0 0 3 1 0 0 3 1 0]
	fmt.Println(zSearch("abracadabra", "abra")) // [0 7]
}

Time: O(n) · Extra space: O(n). The right edge of the box only moves forward, so each letter is newly compared only a handful of times.

Watch out for

  • Forgetting the separator in pattern + "#" + text, so a match can leak across the join.
  • Not trimming the copied value with min(r - i, ...); the echo cannot be trusted beyond the box.
  • Using the separator letter that also appears in the text. Pick one that never occurs.

Quick check

  1. What does z[i] mean?
    • How many times letter i appears
    • How many letters from position i match the start of the word
    • The position of the next match
  2. Why does the algorithm keep a box [l, r)?
    • To sort the letters
    • To reuse old answers for positions inside it
    • To remember the last mismatch
  3. How do we search a pattern inside a text with Z?
    • Sort both strings
    • Run Z on pattern + separator + text and look for z equal to the pattern length
    • Run Z on the text only