Skip to lesson

The Z-algorithm finds substring matches by computing how long of a prefix of the entire string matches starting at each position. We start with plain character-by-character comparison to see why naive prefix checking is slow, and then accelerate it using the Z-box.

Brute Force Prefix Matching and Why It Is Slow

For a string S of length N, the Z-array entry Z[i] is defined as the length of the longest substring starting at S[i] that is also a prefix of S. By definition, Z[0] is typically set to 0 or N.

Java
for (int i = 1; i < n; i++) {    int k = 0;                   // restart from 0 at every index    while (i + k < n && s.charAt(i + k) == s.charAt(k)) k++;    z[i] = k;}// On "AAAAAAAAAA" the inner loop runs (N - 1) + (N - 2) + ... + 1 times: O(N^2)

The brute-force way computes each entry with its own comparison loop.

With naive nested loops, at each index i from 1 to N - 1, you compare S[i + k] with S[k] starting from k = 0 until a mismatch occurs. You set Z[i] = k and move to i + 1. Why is this slow? For repetitive strings like 'AAAAAAAAAA', the inner loop compares almost the entire remaining string at every index. This takes (N - 1) + (N - 2) + ... + 1 comparisons, resulting in quadratic O(N^2) time.

The Z-Box Window Optimization

The Z-algorithm optimizes the computation to strictly O(N) time by maintaining an interval [L, R] known as the Z-box. [L, R] represents the substring with the rightmost boundary R discovered so far that matches a prefix of S.

Example 1 · Z-array by comparing from scratch, brute force: O(N²) time, O(N) space

ZNaiveDemo.javaJava
public class ZNaiveDemo {    static int[] buildZ(String s) {        int n = s.length();        int[] z = new int[n];        for (int i = 1; i < n; i++) {            while (i + z[i] < n && s.charAt(z[i]) == s.charAt(i + z[i])) {                z[i]++;                                  // compare from scratch at every i            }        }        return z;    }
    public static void main(String[] args) {        String s = "abacaba";        int[] z = buildZ(s);        for (int i = 0; i < s.length(); i++) {            System.out.println("z[" + i + "] = " + z[i]);        }    }}
Output
z[0] = 0
z[1] = 0
z[2] = 1
z[3] = 0
z[4] = 3
z[5] = 0
z[6] = 1

What this code does

  • For each i, the while loop counts how many letters match the start of the string.
  • In a string like aaaa every index re-compares almost the whole string.
  • It prints the same Z values as the Z-box version for abacaba.

Example 2 · Z-array with the Z-box, optimal: O(N) time, O(N) space

ZArrayPrintDemo.javaJava
public class ZArrayPrintDemo {    public static int[] buildZ(String s) {        int n = s.length();        int[] z = new int[n];        int l = 0, r = 0;        for (int i = 1; i < n; i++) {            if (i <= r) z[i] = Math.min(r - i + 1, z[i - l]);            while (i + z[i] < n && s.charAt(z[i]) == s.charAt(i + z[i])) z[i]++;            if (i + z[i] - 1 > r) { l = i; r = i + z[i] - 1; }        }        return z;    }
    public static void main(String[] args) {        String s = "abacaba";        int[] z = buildZ(s);        for (int i = 0; i < s.length(); i++) {            System.out.println("z[" + i + "] = " + z[i]);        }    }}
Output
z[0] = 0
z[1] = 0
z[2] = 1
z[3] = 0
z[4] = 3
z[5] = 0
z[6] = 1

What this code does

  • z[2]=1 because suffix 'acaba' shares 1 character ('a') with prefix.
  • z[4]=3 because suffix 'aba' matches prefix 'aba' for length 3.
  • z[6]=1 because suffix 'a' matches prefix 'a' for length 1.
  • Why faster: inside the Z-box, Z[i] is copied from an earlier Z value, so letters already known to match are not compared again.

When computing Z[i], if i > R, we have no prior information. We start matching naively from i, expand the match as far right as possible, and update [L, R] = [i, i + Z[i] - 1]. However, if i <= R, index i lies inside the existing Z-box. Because S[L..R] matches prefix S[0..R - L], the character at index i corresponds to the character at prefix index k = i - L. We can copy Z[k] directly, only expanding naively if the match reaches past R.

Find the bug

Find the Z-box bug

Tap the line that breaks the Z-array.

Inside the Z-box [L, R], Z[i] may be copied from Z[i - L].

Round 1 of 2

Pattern Searching with a Delimiter

How do you search for a pattern P in text T using the Z-array? You concatenate them into a single string with a unique separator that does not appear in either string: S = P + '$' + T.

Example 3 · Pattern search with a Z-array: O(N + M) time, O(N + M) space

ZAlgorithmDemo.javaJava
import java.util.ArrayList;import java.util.List;
public class ZAlgorithmDemo {    public static int[] buildZ(String s) {        int n = s.length();        int[] z = new int[n];        int l = 0, r = 0;
        for (int i = 1; i < n; i++) {            if (i <= r) {                z[i] = Math.min(r - i + 1, z[i - l]);            }            while (i + z[i] < n && s.charAt(z[i]) == s.charAt(i + z[i])) {                z[i]++;            }            if (i + z[i] - 1 > r) {                l = i;                r = i + z[i] - 1;            }        }        return z;    }
    public static List<Integer> search(String text, String pattern) {        List<Integer> matches = new ArrayList<>();        String concat = pattern + "$" + text;        int[] z = buildZ(concat);        int m = pattern.length();
        for (int i = m + 1; i < concat.length(); i++) {            if (z[i] == m) {                matches.add(i - (m + 1));            }        }        return matches;    }
    public static void main(String[] args) {        String text = "baabaa";        String pattern = "aab";        System.out.println("Matches: " + search(text, pattern));    }}
Output
Matches: [1]

What this code does

  • buildZ computes prefix matches in O(N) amortized time using the [L, R] window.
  • Concatenates pattern + '$' + text to prevent cross-boundary overruns.
  • Finds match 'aab' at text index 1.

Next, compute the Z-array for string S in linear O(|P| + |T|) time. Because the separator '$' prevents matches from extending across the boundary, any Z[i] can be at most |P|. Whenever Z[i] == |P| for an index in the text section (i > |P|), it means an exact occurrence of pattern P begins at text index i - (|P| + 1). This simple concatenation strategy solves exact pattern search cleanly without separate failure tables.

Comparing the Z-Algorithm and KMP

Both KMP and the Z-algorithm run in strictly linear O(N + M) time and O(N + M) space. The conceptual difference lies in what they measure: KMP's LPS array tracks prefix-suffix matches, while the Z-array tracks prefix-substring matches.

Example 4 · Longest prefix that is also a suffix with a Z-array: O(N) time

LongestPrefixSuffixZDemo.javaJava
public class LongestPrefixSuffixZDemo {    public static int[] buildZ(String s) {        int n = s.length();        int[] z = new int[n];        int l = 0, r = 0;        for (int i = 1; i < n; i++) {            if (i <= r) z[i] = Math.min(r - i + 1, z[i - l]);            while (i + z[i] < n && s.charAt(z[i]) == s.charAt(i + z[i])) z[i]++;            if (i + z[i] - 1 > r) { l = i; r = i + z[i] - 1; }        }        return z;    }
    public static void main(String[] args) {        String s = "ababa";        int[] z = buildZ(s);        int maxLen = 0;        for (int i = 1; i < s.length(); i++) {            if (i + z[i] == s.length()) {                maxLen = Math.max(maxLen, z[i]);            }        }        System.out.println("Longest prefix-suffix length: " + maxLen);    }}
Output
Longest prefix-suffix length: 3

What this code does

  • An index i has i + z[i] == s.length() if its matching prefix reaches the very end.
  • For 'ababa', index 2 has z[2]=3, reaching the end (2 + 3 = 5).
  • The longest common prefix and suffix is 'aba' of length 3.

The Z-algorithm is often preferred in competitive programming because its definition (longest common prefix starting at index i) is more intuitive than the proper prefix-suffix concept, and its concatenated pattern search requires fewer edge cases. However, KMP operates on streaming text character-by-character without allocating memory for the entire text upfront, making KMP superior for infinite streams and hardware pipelines.

Next step

Check your understanding

10 quick questions