Lesson 37 · Core algorithms

Z Algorithm

For every position, find how far the string from there matches its own start. A box of the furthest match so far lets most values be copied instead of recomputed, so the whole array costs O(n).

Z Algorithm concept diagramA visual explanation of the layout and operations shown in this lesson.Z[i] = how far the string matches its own prefix at iaabaabaZ –Z 1Z 0Z 4Z 1Z 0Z 1prefix aabaZ-box [3, 6]: the same four letters, so Z[3] = 4inside a known box, copy Z from the mirror index and extend only past its right edgethe right edge never moves backwards, so the total work is linear
1

What the Z Array Holds

For a string s of length n, Z[i] is the length of the longest substring starting at i that is also a prefix of s. For s = aabxaab, Z[4] = 3 because "aab" starts at 4 and s also starts with "aab". Z[0] is left undefined (or set to n), since the whole string matches itself.

The Z algorithm builds this whole array in O(n). Computing each value on its own, by comparing from scratch at every position, can take O(n²) on strings like aaaa…a. The Z algorithm avoids that by reusing what earlier matches already proved.

  • Z[i] compares the suffix starting at i with the whole string
  • Z[i] = 0 when s[i] differs from s[0]
  • Values can overlap: on aaaa, Z = –, 3, 2, 1
2

The Box: Reusing Earlier Matches

  1. Set L = R = 0
  2. For each i from 1: if i < R, start Z[i] at min(Z[i − L], R − i); else start at 0
  3. While s[Z[i]] equals s[i + Z[i]], add 1 to Z[i]
  4. If i + Z[i] > R, set L = i and R = i + Z[i]

While scanning, keep the match that reaches furthest right as a box [L, R): s[L..R) is known to equal s[0..R − L). For a position i inside the box, s[i..R) is a copy of s[i − L..R − L), so the answer at the mirror position i − L already says how much of it matches the start.

That copy is trusted only up to the edge of the box. So Z[i] starts at min(Z[i − L], R − i). If Z[i − L] is smaller than R − i, that is the final answer and no character is compared. Otherwise the match reaches the edge, and comparing continues from R. When a match ends past R, it becomes the new box.

  • Mirror position: i − L
  • Cap: R − i, the part of the box still ahead of i
  • Boxes are half-open: R is the first index not known to match
3

Z Algorithm for Pattern Matching

To find a pattern P (length m) in a text T, build Z on P + $ + T, where $ is a character found in neither. Every position with Z[i] = m is a match, starting in the text at offset i − m − 1.

Example: P = aaba, T = aabaabaa. On aaba$aabaabaa the Z array is –, 1, 0, 1, 0, 4, 1, 0, 4, 1, 0, 2, 1. Z = 4 at positions 5 and 8, so the pattern occurs at text offsets 0 and 3. Those two matches overlap, and the Z array reports both with no special handling.

The separator matters. Without it, a match can run from the pattern into the text, Z values exceed m, and a test for Z[i] = m misses real matches. On aabaaabaabaa both matches show up as 5. The Z Function problem and Find the Index of the First Occurrence in a String use exactly this setup.

  • Search string: pattern, separator, text
  • Match wherever Z[i] equals the pattern length
  • Text offset = i − (m + 1)
Key reference

Terms, operations, and practical uses

The array

  • Z[i]Length of the longest substring starting at i that equals a prefix of the string.
  • Z[0]Undefined by convention, or n; it never helps a search.
  • SeparatorA character in neither pattern nor text, so no Z value can exceed the pattern length.

The box

  • Box [L, R)The match reaching furthest right so far; s[L..R) equals s[0..R − L).
  • MirrorPosition i − L, whose Z value describes s[i..R) for free.
  • Cap R − iHow much of the copy the box can vouch for; compare characters only past it.

Cost

  • Successful comparisonHappens only past R and moves R right, so at most n in total.
  • Failed comparisonEnds the loop for that position, so at most one per position.
  • TotalO(n) for the array, O(n + m) to search a text of length n for a pattern of length m.
Implementation

Code in Python, C++ and Java

def z_array(s):
    n = len(s)
    z = [0] * n
    left = right = 0
    for i in range(1, n):
        if i < right:
            z[i] = min(z[i - left], right - i)
        while i + z[i] < n and s[z[i]] == s[i + z[i]]:
            z[i] += 1
        if i + z[i] > right:
            left, right = i, i + z[i]
    return z


def find_all(pattern, text):
    m = len(pattern)
    z = z_array(pattern + "$" + text)
    return [i - m - 1 for i in range(m + 1, len(z)) if z[i] == m]


print("Z:", *z_array("aaba$aabaabaa"))
print("Matches at:", *find_all("aaba", "aabaabaa"))
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;

vector<int> zArray(const string& s) {
    int n = s.size(), left = 0, right = 0;
    vector<int> z(n, 0);
    for (int i = 1; i < n; i++) {
        if (i < right) z[i] = min(z[i - left], right - i);
        while (i + z[i] < n && s[z[i]] == s[i + z[i]]) z[i]++;
        if (i + z[i] > right) {
            left = i;
            right = i + z[i];
        }
    }
    return z;
}

vector<int> findAll(const string& pattern, const string& text) {
    int m = pattern.size();
    vector<int> z = zArray(pattern + "$" + text), found;
    for (int i = m + 1; i < (int)z.size(); i++)
        if (z[i] == m) found.push_back(i - m - 1);
    return found;
}

int main() {
    cout << "Z:";
    for (int v : zArray("aaba$aabaabaa")) cout << " " << v;
    cout << "\nMatches at:";
    for (int p : findAll("aaba", "aabaabaa")) cout << " " << p;
    cout << "\n";
}
import java.util.ArrayList;
import java.util.List;

public class Main {
    static int[] zArray(String s) {
        int n = s.length(), left = 0, right = 0;
        int[] z = new int[n];
        for (int i = 1; i < n; i++) {
            if (i < right) z[i] = Math.min(z[i - left], right - i);
            while (i + z[i] < n && s.charAt(z[i]) == s.charAt(i + z[i])) z[i]++;
            if (i + z[i] > right) {
                left = i;
                right = i + z[i];
            }
        }
        return z;
    }

    static List<Integer> findAll(String pattern, String text) {
        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);
        return found;
    }

    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("Z:");
        for (int v : zArray("aaba$aabaabaa")) sb.append(" ").append(v);
        sb.append("\nMatches at:");
        for (int p : findAll("aaba", "aabaabaa")) sb.append(" ").append(p);
        System.out.println(sb);
    }
}
Watch it run

Step through it

Running on pattern "aaba", text "aabaabaa", search string aaba$aabaabaa

Z[i] = how far s[i...] matches s[0...]patternseptexta0–a1b2a3$4a5a6b7a8a9b10a11a12iZa match of the pattern starts wherever Z[i] = 4Z[0] is left undefined: the whole string trivially matches itself
Step 1

Pattern + separator + text

To find "aaba" in "aabaabaa", join them as aaba$aabaabaa. Z[i] will be the length of the longest stretch starting at i that matches the start of the string. The $ appears in neither input, so no match can run across it, and every Z value stays at most 4, the pattern length.

Output
1 / 12
4

Z Algorithm Time Complexity

The loops look nested, but the total work is linear. Look at each character comparison. A failed comparison ends the loop, so there is at most one per position: under n. A successful comparison happens only beyond R, because everything before R was copied. Each one moves R right by one, and R never moves left, so there are at most n of those.

That gives O(n) time for a string of length n, and O(n + m) for pattern search. Memory is the Z array itself, O(n + m). On aaba$aabaabaa the algorithm makes 16 comparisons where the naive scan makes 25; on a string of 1,000 a's it makes 999 where the naive scan makes 499,500.

  • Failed comparisons: at most one per position
  • Successful comparisons: at most n, because each moves R right
  • Time O(n + m), memory O(n + m)
5

Z Algorithm vs KMP

Both find all matches in O(n + m) and both learn from the pattern's repeated parts. They store different facts. The Z array says, for every position, how far the string matches its own start. KMP stores, for every prefix of the pattern, where to resume after a mismatch.

Two linear-time matchers compared
Z arrayKMP
What each entry meansMatch length with the prefix at position iFallback position inside the pattern
Search setupOne array over pattern + $ + textTable on the pattern, then scan the text
Needs a separatorYesNo
Text arriving as a streamAwkward: needs the joined stringNatural: one character at a time
Memory for searchO(n + m)O(m)
  • Pick Z when you want match lengths at every position
  • Pick KMP for streams or when memory must stay O(m)
  • Both are exact; string hashing is faster to write but can be wrong
6

Other Uses of the Z Array

A position i with i + Z[i] = n means the suffix from i equals a prefix of the same length, so the string has a border there. The smallest such i that also divides n is the string's shortest period: "abcabc" has Z[3] = 3 and 3 + 3 = 6, so it is "abc" repeated twice.

Adding one character to a string creates new distinct substrings; reversing the new string and taking the largest Z value counts them in O(n), which gives O(n²) for counting all distinct substrings. The same idea checks whether one string is a rotation of another: search for it in the other string doubled.

  • i + Z[i] = n: suffix at i equals a prefix
  • Shortest period: smallest such i that divides n
  • Rotation check: find B in A + A
7

Common Mistakes

Most wrong Z arrays come from one of these.

  • Copying Z[i − L] without the R − i cap, which claims characters the box never checked
  • Forgetting to update L and R when a match passes R
  • Indexing past the end: check i + Z[i] < n before comparing
  • Using a separator that can appear in the input
  • Converting a match position back to the text without subtracting m + 1