Skip to the workspace
Pebellslearn by building
String Algorithms  ›  Lesson

The Z Algorithm

The Z Algorithm 28 minInside the Z-box, values are copied from their mirror, so each character is compared only a constant number of times

dsa / The Z Algorithm

Explore each scene at your own pace.

01 · The Z-array

The Z-array

The Z Algorithm

Definition
The Z algorithm computes, for each position of a string, the length of the longest match between the text starting there and the start of the string. It reuses a box of known matches to run in O(n), and can search by joining a pattern, a separator and a text.
In plain words
For every position it asks how many letters from here repeat the very beginning of the string. A remembered box of already-matched letters lets it copy earlier answers instead of recounting them.

In short: the Z-array answers the mirror question to KMP's — z[i] is how far the string starting at i copies the string's own beginning. A Z-box [l, r) remembers the furthest-right match found so far; inside it, a new value starts at min(r − i, z[i − l]) from its mirror position and only extends past what's already known, which keeps the whole scan at O(n). Gluing pattern + separator + text and reading where z equals the pattern's length turns the same algorithm into a search.

![A Z-box 4, 7) on "aabaaab"; z[5] is copied from its mirror z[1] = 1 with no character comparison

KMP answers "how much of the pattern is matched ending here?" The Z algorithm answers the mirror-image question: "how much of the string's beginning is repeated starting here?" Both run in linear time. Z is often the easier of the two to get right under pressure, because its invariant is something you can draw: a box.

The Z-array

For a string s, z[i] is the length of the longest common prefix of s and s[i:], meaning how many characters starting at i copy the start of the string. By convention here z[0] = len(s), since the whole string trivially copies itself.

i 0 1 2 3 4 5 6
s a a b a a a b
z 7 1 0 2 3 1 0

z[4] = 3 because s[4:] is aab, which starts the same way as s for three characters. z[2] = 0 because b doesn't match a at all.

In Quarry this is the prefix profiler. For every position in a block of text, it says how far the text there echoes a given beginning. Pattern search comes straight out of it: glue the pattern, a separator and the text together, and every position where z equals the pattern's length is a match.

The direct way compares from scratch at every position:

python
What does this print?
s = "aaaa"
z = [len(s)]
for i in range(1, len(s)):
    k = 0
    while i + k < len(s) and s[k] == s[i + k]:
        k += 1
    z.append(k)
print(z)
Scene 1 of 11
Project context and further resources
You're building a piece ofQuarry — the text index
This piece — z_array(): For every position, how far the text there repeats its own beginning.
Scenario A user starts typing "disk f" into Quarry's search box. For every position in the log, the prefix profiler already knows how much of the query's beginning appears there, so it can rank suggestions without scanning again.
z_array.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
z_array(s) → listFor each position, how many characters starting there copy the start of the string.
try:
returned
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.