The Z-function
1 How far does the start match here?
The KMP lesson searched for a pattern by asking, at each letter of the text, how much of the pattern ends there. The Z-function asks the other way round. Starting at this index, how much of the string's own beginning do we see?
Take the string s = "aabaabaaab". At index 3 it reads aabaa, and s itself also starts with aabaa. Five letters agree before the two part. At index 1, only one letter agrees.
That number, for every index, is the Z-array. z[i] is the length of the longest stretch starting at i that matches the start of s. The start of s is its prefix.
This one array answers a pattern search. If we put the pattern in front of the text, every index where z reaches the pattern's length is a match.
2 Sliding a copy of s under itself
The picture to keep is a second copy of s, slid to the right. To find z[i], we lay the copy so that its first letter sits under index i. Then we read both rows from left to right and count the letters that agree, until the first difference or the end of s.
Doing this at every index gives the whole array:
z[0] is a special case. The whole string matches itself, so some write n there. We leave it at 0, and the algorithm never reads it. When a problem asks for the array, its statement says which one it wants.
Done this way, each index compares letters from scratch. On a string of 10⁵ copies of a, every copy agrees to the end, and that is around 5 × 10⁹ comparisons. At about 10⁸ steps a second, it gets Time Limit Exceeded (TLE).
3 Reusing the window
Look at i = 3 again. Letters 3 to 7 matched letters 0 to 4. So the stretch from 3 to 7 is a copy of the start of s. We already know the z-values at the start of s. Inside the copy, the same answers hold, as long as they stay inside it.
We keep this stretch as a window [l, r). Its first letter is at l, and r is one past its last letter. Of all the matches found so far, the window is the one that reaches furthest right. After i = 3, l = 3 and r = 3 + 5 = 8.
For an index i inside the window, the text from i to r is the same as the text from i − l to r − l. A match at i − l is already known: z[i − l]. So z[i] starts from
The min matters. Past r we know nothing about s yet, so we can copy at most r − i letters. Three cases come out of it:
- z[i − l] < r − i. The copied match ends inside the window, and so does the difference that stopped it. z[i] is exactly z[i − l].
- z[i − l] > r − i. The copy is cut at r. The letter at r stopped the window's own match, and it also stops this one, so z[i] is exactly r − i.
- z[i − l] = r − i. The copy reaches r exactly. Past r we compare letters as before, and the match may grow.
The code does not need the three cases. It starts from the min, or from 0 outside the window, and compares onward. When a match ends past r, that match becomes the new window.
In the steps below, the bottom row is the copy of s laid under l. Blue is the window, and orange is what we copy for free.
At i = 6 the copy says 5, but only 2 letters of it lie inside the window. The letter at 8 is a, and the prefix has b at 2, so z[6] really is 2.
4 Tracing it, and why it is O(n)
Here is every index of "aabaabaaab". The start column is what we copy, and the extra column is the letters we had to compare and found equal.
| i | window [l, r) | start | extra | z[i] |
|---|---|---|---|---|
| 1 | [0, 0) | 0 | 1 | 1 |
| 2 | [1, 2) | 0 | 0 | 0 |
| 3 | [1, 2) | 0 | 5 | 5 |
| 4 | [3, 8) | min(4, z[1]) = 1 | 0 | 1 |
| 5 | [3, 8) | min(3, z[2]) = 0 | 0 | 0 |
| 6 | [3, 8) | min(2, z[3]) = 2 | 0 | 2 |
| 7 | [3, 8) | min(1, z[4]) = 1 | 2 | 3 |
| 8 | [7, 10) | min(2, z[1]) = 1 | 0 | 1 |
| 9 | [7, 10) | min(1, z[2]) = 0 | 0 | 0 |
The window column is the window when i arrives. The extra column is the real work, and it adds up to 8, less than n = 10.
Why O(n). Each index makes at most one comparison that fails, the one that stops it. Every comparison that succeeds reads a letter at or past r, and then the window moves beyond it. r only moves right and never passes n, so the successes add up to at most n. In all, that is at most 2n comparisons, so the loop is O(n). The z-array takes O(n) space.
5 Pattern matching with p + '#' + t
To find a pattern p of length m in a text t of length n, we build one string: p, then a separator, then t. The separator is a character that appears in neither string. We use #, the same trick as in the KMP lesson.
At an index in the t part, z counts how far the text there agrees with the start of the joined string, and that start is p. No letter of t equals #, so no match can run past p. So z == m means the whole pattern starts there. Index i in the joined string is index i − m − 1 in t.
With p = "aab" and our s as the text:
KMP finds the same matches. The two arrays answer mirror questions:
| KMP's LPS | Z-array | |
|---|---|---|
| Entry i holds | the longest prefix that ends at i | the longest prefix that starts at i |
| Reads the text | once, left to right | as part of one joined string |
| Search cost | O(n + m) time, O(m) space | O(n + m) time and space |
| Easier for | text that arrives one letter at a time | how far the prefix matches at each index |
Both are linear, so the choice is about fit. Z is often easier to get right in an interview, because z[i] means just what it says.
6 The code
zFunction follows the trace line by line. findAll joins the strings and collects every index where z == m.
On "aabaabaaab", zFunction returns [0, 1, 0, 5, 1, 0, 2, 3, 1, 0], and findAll with "aab" returns [0, 3, 7]. The joined string has n + m + 1 letters, so the search takes O(n + m) time and space.
7 Mistakes and edge cases
- A separator that can occur. With p =
"ab"and t ="ab#ab", the joined string is"ab#ab#ab". At the first match, z runs on through the next#to 5, soz == mmisses it and only 3 is found. Pick a character the input never contains. - Copying z[i − l] without the min. On
"aabaabaaab"this sets z[6] = z[3] = 5. The true value is 2, because the copy only holds up to r. - Off by one on the window. r is one past the match, so r − i letters fit. Writing r − i + 1 with this r gives z[6] = 3 on the same string.
- Starting the loop at 0. Then z[0] becomes n and the window becomes [0, n). Every later i copies z[i − 0], its own entry, which is still 0. So nothing is reused. The answers stay right, but the run is O(n²) again.
8 More from one Z-array
The same array answers more than one search:
- Count matches. Count the indexes where z == m instead of listing them.
- The smallest period. A string has period k when every letter equals the letter k places later. The smallest k with k + z[k] == n is the smallest period, and it is n when there is none. For
"abcabcab", z[3] = 5 and 3 + 5 = 8, so the period is 3. - Compression. s is one block repeated when its smallest period divides n.
"abcabc"is"abc"twice. - The longest prefix that is also a suffix. It has length n − k, for that same smallest period k.
- Distinct substrings. Add one letter at a time, and take z of the string so far, reversed. The new letter adds its length minus the largest z-value as new substrings. In all, that is O(n²).
- A match with one wrong letter. z of p +
#+ t gives the matching prefix at each start, and the same on both strings reversed gives the matching suffix. A start works when the two add up to at least m − 1.
The sign for this lesson is a question about the start of a string at every index: where a pattern begins, how often a block repeats, or how much of one string's start appears inside another. The next lesson compares stretches of text by a single number instead, with rolling hashes.
Practice it
Finished this lesson?
Mark it read and it is ticked on the roadmap and in the list.