Algorithms · Visualized

String: Z-algorithm

String Matching

Find a pattern inside a text efficiently — from the naive slide to prefix-function smartness.

The Z-algorithm builds a 'Z-array' where Z[i] tells you the length of the longest substring starting at position i that matches a prefix of the string. Time: O(n + m) average, O(n + m), where n = text length, m = pattern length worst; space: O(n + m) — combined string and Z-array.

Big-O: Naive O(n·m); KMP & Z O(n+m); Rabin–Karp O(n+m) average with hashing.

Z-Algorithm

String Matching

The Z-algorithm builds a 'Z-array' where Z[i] tells you the length of the longest substring starting at position i that matches a prefix of the string. By concatenating pattern + a separator + text and computing the Z-array of that combined string, any position where Z[i] equals the pattern's length marks a match.

How Z-algorithm Works

  1. Concatenate the pattern, a separator character not found in either string (like '
    #x27;), and the text into one combined string.
  2. Compute the Z-array for this combined string: maintain a window [L, R] representing the rightmost match found so far, and use previously computed Z-values to avoid redundant comparisons where possible.
  3. For each new position, either reuse information from the current [L,R] window, or extend the comparison character by character when outside that window.
  4. Whenever a Z-value equals the pattern's length, that position (adjusted for the pattern length and separator) marks a match in the original text.
  5. Collect all such positions as the full list of matches.

Z-algorithm Worked Example

Input: {text: aabxaabxcaabxaabxay, pattern: aabx}

Combined string: 'aabx$aabxaabxcaabxaabxay'. Computing the Z-array, positions where a Z-value of 4 (the pattern length) appears correspond to matches. This finds pattern matches at indices 0, 4, 9, and 13 in the original text.

String: Z-algorithmO(n + m)
Z[i] = longest substring from i matching the prefix — search in linear time.
t
a
a
b
x
$
a
a
b
x
a
a
b
x
c
a
a
b
x
a
a
b
x
a
y
01234567891011121314151617181920212223
Step 1 / 7
Default Current / Compare Swap / Write Settled Active / Path Pivot / Reject Locked (hollow) Target
Z-algorithm on "aabx$aabxaabxcaabxaabxay" — Z[i] = longest prefix of S that starts at i.
Python · String Matching in Code
def z_algorithm(text, pat):
    s = pat + '#' + text
    z = [0] * len(s)
    l = r = 0
    for i in range(1, len(s)):
        if i <= r:
            z[i] = min(r - i + 1, z[i - l])
        while i + z[i] < len(s) and s[z[i]] == s[i + z[i]]:
            z[i] += 1
        if i + z[i] - 1 > r:
            l, r = i, i + z[i] - 1
    return [i - len(pat) - 1 for i, v in enumerate(z) if v == len(pat)]

Behind the Scenes Execution

Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.

Z-algorithm Time & Space Complexity

BestO(n + m)
AverageO(n + m)
WorstO(n + m), where n = text length, m = pattern length
SpaceO(n + m) — combined string and Z-array

When to Use Z-algorithm

  • Fast substring search alternative to KMP, and useful for finding all occurrences of multiple patterns via variations.
  • Used in solving related string problems like finding the shortest repeating unit of a string.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Keep the momentum going

Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.