Z function
Pattern: Pattern matching
Build the Z-array of pattern + "$" + text. z[i] is how far the string starting at i matches the start of the whole string. Wherever z[i] is at least the pattern's length, the pattern occurs.
The problem
Given a text and a pattern, return every index where the pattern starts in the text, in increasing order, using the
Z-function. Indexes count from 0. For example, "xyzabxyzabxyz" with "xyz" gives [0, 5, 10], and "cabcdab" with
"abc" gives [1].
The function name search matches the takeUforward practice page. Use the link above for the exact statement and
limits. An empty list means no match.
Think first
- If you knew, for every position of the text, how long a prefix of the pattern starts there, how would you find matches?
- Why join the pattern and the text with a character that appears in neither?
- When computing
z[i], what does an earlier long match tell you for free?
Hints
Brute force, and why it fails
Compute each z[i] by comparing from scratch: O(n²) in the worst case (all equal characters). Reusing the window makes
it O(n + m).
The key insight
Inside a known match window, the string repeats its own beginning. So most of each z[i] can be copied from an earlier
value, and only new characters past r are ever compared.
Dry run
text = cabcdab and pattern = abc. Join them as abc$cabcdab. The $ stops matches running across the join.
The plan
s = pattern + "$" + text
z = zeros, l = 0, r = 0
for i from 1 to len(s) - 1:
if i < r: z[i] = min(r - i, z[i - l])
while i + z[i] < len(s) and s[z[i]] == s[i + z[i]]: z[i] = z[i] + 1
if i + z[i] > r: l = i; r = i + z[i]
return every i - m - 1 with i > m and z[i] >= m
Complexity
- Time
O(n + m)- Space
O(n + m)
Every successful comparison moves r right, and r never moves back. The joined string and the Z-array take O(n + m).
Edge cases
- Pattern longer than text: no matches.
- Overlapping matches, as in
"aaabaaaabaaa"with"aa". - The separator must not appear in either string.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public List<Integer> search(String text, String pattern) {
String s = pattern + "$" + text; // '$' appears in neither string
int n = s.length(), m = pattern.length();
int[] z = new int[n]; // z[i] = longest match of s starting at i with the start of s
for (int i = 1, l = 0, r = 0; i < n; i++) {
if (i < r) z[i] = Math.min(r - i, z[i - l]); // reuse what the window [l, r) already shows
while (i + z[i] < n && s.charAt(z[i]) == s.charAt(i + z[i])) z[i]++;
if (i + z[i] > r) { l = i; r = i + z[i]; }
}
List<Integer> out = new ArrayList<>();
for (int i = m + 1; i < n; i++) if (z[i] >= m) out.add(i - m - 1); // the whole pattern matches here
return out;
}
}C++
class Solution {
public:
vector<int> search(string text, string pattern) {
string s = pattern + "$" + text; // '$' appears in neither string
int n = static_cast<int>(s.size()), m = static_cast<int>(pattern.size());
vector<int> z(n, 0); // z[i] = longest match of s starting at i with the start of s
for (int i = 1, l = 0, r = 0; i < n; i++) {
if (i < r) z[i] = min(r - i, z[i - l]); // reuse what the window [l, r) already shows
while (i + z[i] < n && s[z[i]] == s[i + z[i]]) z[i]++;
if (i + z[i] > r) { l = i; r = i + z[i]; }
}
vector<int> out;
for (int i = m + 1; i < n; i++) if (z[i] >= m) out.push_back(i - m - 1); // the whole pattern matches
return out;
}
};Python
class Solution:
def search(self, text: str, pattern: str) -> list[int]:
s = pattern + "$" + text # '$' appears in neither string
n, m = len(s), len(pattern)
z = [0] * n # z[i] = longest match of s starting at i with the start of s
l = r = 0
for i in range(1, n):
if i < r:
z[i] = min(r - i, z[i - l]) # reuse what the window [l, r) already shows
while i + z[i] < n and s[z[i]] == s[i + z[i]]:
z[i] += 1
if i + z[i] > r:
l, r = i, i + z[i]
return [i - m - 1 for i in range(m + 1, n) if z[i] >= m] # the whole pattern matches hereCommon mistakes
- Leaving out the separator, so a match can run from the pattern into the text.
- Starting
z[i]atz[i - l]without capping it atr - i. - Converting back with
i - minstead ofi - m - 1.