How the Z-algorithm boxes previous prefix matches

Short answer: The Z-algorithm computes, for every index i of a string s, the length Z[i] of the longest substring starting at i that matches a prefix of s. It does this in O(n) time by reusing a window [left, right] that is the rightmost prefix match found so far. Inside that window, a previous Z value copies across, and only the characters past right are compared. Pattern search concatenates the pattern, a separator, and the text, and reads the Z values that equal the pattern length.


What the problem actually asks

KMP stores the longest border of each prefix. The Z-array stores the longest prefix match at each position, which is a different table and a more direct statement of “how much of the pattern sits here.” Computing it naively is quadratic. The linear algorithm keeps the segment of the string that is already known to equal a prefix, so a position inside that segment can inherit a Z value from the corresponding position inside the prefix.

When the inherited match would stick out of the known segment, the algorithm compares from the edge. When it falls strictly inside, the inherited value is exact and no comparison happens.


What the algorithm guarantees

The array is correct and the scan performs O(n) character comparisons, because each comparison that advances right is charged to a new index and the right endpoint never moves left. Extra memory is the array. For pattern matching, build s = pattern + separator + text, where the separator appears in neither. An index i in the text portion with Z[i] equal to the pattern length is a match. Overlapping matches are separate indices and all of them appear.

The separator has to be absent from both strings, or a prefix match can run through the boundary and report a false occurrence. If no extra alphabet symbol exists, the match check can stop at length m without a separator, provided the Z computation is run on the pattern alone and then applied to the text in the same boxed way. Both formulations are linear.


The working steps

  1. Set Z[0] = 0 by convention. The whole string matches itself and is not a useful value.
  2. Maintain [left, right], initially empty, as the rightmost segment that matches a prefix.
  3. For i from 1 to n−1, if i is inside the segment, set Z[i] to the minimum of Z[i−left] and right−i+1. If that value reaches the edge of the segment, compare further characters and extend.
  4. If i is outside the segment, compare s[i], s[i+1], … with the prefix directly.
  5. Whenever a match extends to or past right, replace [left, right] with the new segment. To search, run this on pattern, separator, and text, and report every text index whose Z value equals the pattern length.

The linear bound is deterministic worst case, like KMP. The Z-array is not the prefix table, and substituting one for the other off by a definition produces wrong shifts. Pattern search needs a boundary between pattern and text. Rabin-Karp is the hash alternative, with collisions. The Z-algorithm does not approximate.


Approaches that look simpler and fail

Approach Why it fails when the boxed copy ignores the window edge
Copy Z[i−left] even when it exceeds the remaining window The characters past right have not been verified. The copied length has to be cut at the window, and only then may comparisons resume.
Omit the separator between pattern and text A Z value can count characters from both sides of the boundary and look longer than the pattern, or a prefix of the text can be confused with the pattern.
Set Z[0] to n and then treat it as a match at the start The start is a match only if the pattern equals the text’s prefix, which the concatenation encodes at the text’s index, not at index 0.
Recompute every Z[i] with a fresh scan and quote O(n) The fresh scan is the quadratic algorithm. The window is what makes the linear bound true.

Border-based linear search is KMP. Right-to-left skipping is Boyer-Moore. The Z-array is the prefix-match table, and it is also the tool used to build other string structures that need every prefix length.


A working example

This Python fragment fills the Z array. A copied length is capped at the right edge of the current window. It prints 0 1 0 0 2 1 0 for aabxaay. The pattern search would put a separator between pattern and text.

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(right - i, z[i - left])
        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

s = "aabxaay"
naive = [0] * len(s)
for i in range(1, len(s)):
    while i + naive[i] < len(s) and s[naive[i]] == s[i + naive[i]]:
        naive[i] += 1
assert z_array(s) == naive == [0, 1, 0, 0, 2, 1, 0]
print(*z_array(s))

Where it is used

The Z-algorithm builds the prefix-match boxes used by linear-time exact matchers and by other string algorithms that need the same borders KMP computes. It is a construction tool more than a user-facing search command. Boyer-Moore and Aho-Corasick are the scanners a search tool ships.


When you can drop this algorithm

Drop the Z-algorithm when an existing KMP or library search already solves the single-pattern problem and the array itself is not needed. Keep it when every position’s prefix-match length is the object of interest, or when a linear scan with an explicit window is the implementation you want.


Why this stays published

We publish this so a search for the Z-algorithm returns the rightmost window and the rule that a copied value cannot extend past it unverified. The Z-algorithm computes every prefix-match length in linear time by copying values inside a verified window and comparing only at its edge.

本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。

Leave a Reply

Your email address will not be published. Required fields are marked *