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 MatchingThe 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
- Concatenate the pattern, a separator character not found in either string (like '#x27;), and the text into one combined string.
- 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.
- For each new position, either reuse information from the current [L,R] window, or extend the comparison character by character when outside that window.
- 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.
- 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.
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
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
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.