Z Function
Z Function is a GFG problem (Medium). For a string s of length n, build an array Z where Z[i] is the length of the longest substring starting at index i that is also a prefix of s.
Z[0]is set to 0 by convention, because the whole string trivially matches itself.- The follow-up is pattern search: return every 0-based index where
patoccurs intxt. - With
nup to 10⁵, checking each index from scratch is too slow on strings like"aaaa…a". The target is O(n).
- 1 <= s.length <= 10⁵
- Pattern search: 1 <= pat.length <= txt.length, lowercase letters only
Intuition
Comparing every index against the prefix from scratch repeats work. Once you find that s[l..r] equals s[0..r−l], every index inside that stretch is a copy of an index near the front, so its answer is mostly known already.
- The Z-box: keep
[l, r], the match that reaches furthest right so far. - The mirror: for
iinside the box, indexi − lsits at the same place in the prefix, soZ[i]starts atmin(Z[i − l], r − i + 1). - The extension: only letters past
rare compared directly, and each successful comparison pushesrright. Sinceronly grows, the whole run does O(n) comparisons.
Any question of the form "how far does the text starting here agree with the start of the string?" is a Z array question. Exact pattern search, finding the shortest period of a string and counting how often prefixes repeat all reduce to it.
Approach
Before reading on, write the Z array of "aabaaab" by hand, comparing each index from scratch. Then look at index 4: was there any comparison you had already done while working out index 3?
Start with an empty box
Create z filled with zeros and set l = r = 0. With r = 0, no index from 1 onward is inside the box, so the first index is always compared from scratch.
Copy from the mirror when inside the box
For each i from 1, if i <= r, set z[i] = min(z[i - l], r - i + 1). The box guarantees letters up to r match the prefix, but says nothing past r, so the copied value can never reach beyond the box.
Extend by direct comparison
While i + z[i] < n and s[z[i]] == s[i + z[i]], add 1 to z[i]. This checks only letters the box did not cover, and stops at the first mismatch or the end of the string.
Move the box when the match reaches further
If i + z[i] - 1 > r, set l = i and r = i + z[i] - 1. Keeping the box that reaches furthest right lets later indices copy as much as possible without comparing.
Search a pattern with a separator
Build s = pat + "$" + txt and its Z array. Any index with z[i] == len(pat) starts a full copy of the pattern, at text index i - len(pat) - 1. The $ appears in neither string, so no value can exceed the pattern length.
Code in Python, C++ and Java
Common pitfalls
Copying the mirror value without the cap
if i <= r:
z[i] = z[i - l]if i <= r:
z[i] = min(z[i - l], r - i + 1)For "aaaab" the box after index 1 is [1, 3] and z[1] = 3. At index 2 the uncapped copy gives 3, claiming "aab" equals "aaa". The cap gives 2, and the comparison of a with b then correctly stops there.
Moving the box on every index
l, r = i, i + z[i] - 1
if i + z[i] - 1 > r:
l, r = i, i + z[i] - 1A short match found later pulls r back to the left. In "aabaaab" the box [4, 6] shrinks to [5, 5] at index 5, so index 6 loses its free start and is compared from scratch. The values stay correct, but the O(n) bound relies on r only moving right.
Joining pattern and text without a separator
s = pat + txt
s = pat + "$" + txt
With pat = "aa" and txt = "aaa", the joined "aaaaa" has z[2] = 3: the match runs on past the pattern length, so z[i] == m misses the occurrence at text index 0. The $ matches no letter, so no value can go above m.
Edge cases
"aaaaa"Index 1 compares its way to the end, and every later index copies its whole answer from the mirror. Z is [0, 4, 3, 2, 1] after only a handful of comparisons.
"aa" in "baaa"Z values at consecutive indices can both equal the pattern length, so both start positions, 1 and 2, are reported.
Complexity
r one step right and r never decreases, so there are at most n of them. Each index adds at most one failed comparison. Pattern search runs on a string of length m + n + 1, so it is O(m + n).Z array, KMP and a plain scan
All three find every copy of a pattern. They differ in what they compute first and what they keep in memory.
| Method | Computed first | Time | Extra space | Best when |
|---|---|---|---|---|
| Z array (this page) | Z values of pat + "$" + txt | O(n + m) | O(n + m) | you also want prefix-match lengths at every index |
| KMP search | a border table of the pattern only | O(n + m) | O(m) | the text arrives as a stream |
| Plain scan | nothing | O(n·m) worst case | O(1) | the pattern is short and the input is friendly |
Z Function FAQ
How is the Z array different from the KMP prefix table?
Both describe how a string overlaps its own start. Z looks forward: from index i, how far does the text match the prefix? The prefix table looks backward: which prefix ends at index i? Each can be converted into the other in O(n).
Why is index 0 set to 0?
The substring starting at 0 is the whole string, which matches itself for all n letters. That value tells you nothing, so most write-ups store 0 (some store n). The algorithm never reads z[0], because the box always starts at l >= 1.
Can the Z array find the shortest repeating unit of a string?
Yes. The smallest p that divides n and has p + z[p] == n is the period, since the string then equals itself shifted by p. If no such p exists, the string does not repeat.