Z-Function (Z-Algorithm)
For every position of a string, find how far it matches the string's own start, then use that to search for a pattern.
Given a string sziz[i]sisz[0] = n
Example 1
Output: z = [6, 1, 0, 0, 2, 1]
Explanation: at index 4, "aa" is the same as the first two characters "aa", so z[4] = 2.
Example 2
Output: [1, 4, 7]
The Idea
When you press Ctrl+F in an editor and type a word, the editor finds every place the word appears in the text. Example 2 asks for exactly that: "abc" appears in "aabcabcabc" at indexes 1, 4 and 7. The Z-array is a tool that gives such a search in a single pass.
The start of a string, of any length, is called a prefix: "a", "aa" and "aab" are prefixes of "aabxaa". The Z-array records, for every position, how long a prefix begins there. Take s = "aabxaa"sz[1] = 1z[4] = 2
Comparing character by character from every position is slow when the string repeats. In "aaaaa", index 1 matches 4 characters, index 2 matches 3, and so on. Back in "aabxaa", once index 4 has matched "aa", we know the two characters from index 4 are a copy of the two at index 0. Can the answer for index 5 be read from that copy instead of compared again?
Look at the picture below. The orange bracket marks the match found at index 4, from index 4 up to, but not including, index 6. Call it the box, with left end l = 4r = 6[4, 6)
Index 5 is the second character of the box, so it sits at the same spot as index 1 in the prefix: 5 - l = 1z[1] = 1z[5]
The copy can only be trusted up to the box's right end, though. Past ri = 5r - i = 6 - 5 = 1
Solution Approach
Turning that idea into code means settling four things: why the simple way is slow, which box to keep, how to fill one position from the box, and how the Z-array finds a pattern in a text.
The simple way
Why not just compare from every position? For each is[i], s[i+1], ...s[0], s[1], ...i
Which box to keep
Which earlier match should we remember? The one that reaches furthest right. Every match is a copy of a prefix, and the one with the largest rr
Filling one position
What happens at a position iiz[i]min(r - i, z[i - l])ir
Each successful comparison happens at or beyond rr
Searching for a pattern
How does an array about prefixes find a pattern? Join the pattern, a separator character such as $
The separator must appear in neither string. Then any match starting in the text stops at the latest when it reaches $ii - m - 1$
Java Solution
The method zArray
- First, create the array
with one entry per character, return it empty for an empty string, and setz to n.z[0] - Start the box as empty, with
andl both 0. Then a loop movesr from 1 to the end of the string.i - If
is inside the box (i ), seti < r toz[i] , the capped copy from the prefix.Math.min(r - i, z[i - l]) - Still inside that loop, a second loop, a
loop, compareswhile withs.charAt(z[i]) and adds 1 tos.charAt(i + z[i]) as long as they are equal.z[i] - If the match now ends past
, it becomes the new box:r andl = i . After the last position, returnr = i + z[i] .z
The method searcht = pattern + "$" + textzArrayi - m - 1resultiz[i] >= m
The main
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ZFunction {
// z[i]: length of the longest substring starting at i that matches a prefix of s
public static int[] zArray(String s) {
int n = s.length();
int[] z = new int[n];
if (n == 0) {
return z;
}
z[0] = n;
int l = 0;
int r = 0; // s[l..r) is the rightmost match found so far
for (int i = 1; i < n; i++) {
if (i < r) {
z[i] = Math.min(r - i, z[i - l]); // reuse the value from inside the prefix
}
while (i + z[i] < n && s.charAt(z[i]) == s.charAt(i + z[i])) {
z[i]++; // extend by direct comparison
}
if (i + z[i] > r) {
l = i;
r = i + z[i];
}
}
return z;
}
public static List<Integer> search(String text, String pattern) {
String t = pattern + "$" + text; // '$' appears in neither string
int[] z = zArray(t);
List<Integer> result = new ArrayList<>();
int m = pattern.length();
for (int i = m + 1; i < t.length(); i++) {
if (z[i] >= m) {
result.add(i - m - 1);
}
}
return result;
}
public static void main(String[] args) {
System.out.println(Arrays.toString(zArray("aabxaa")));
System.out.println(search("aabcabcabc", "abc"));
System.out.println(Arrays.toString(zArray("aaaaa")));
System.out.println(Arrays.toString(zArray("aaab")));
System.out.println(search("aaa", "aa"));
System.out.println(search("abc", "abcd"));
System.out.println(Arrays.toString(zArray("")));
}
}
Running it prints:
[6, 1, 0, 0, 2, 1]
[1, 4, 7]
[5, 4, 3, 2, 1]
[4, 2, 1, 0]
[0, 1]
[]
[]
The array [6, 1, 0, 0, 2, 1][1, 4, 7][5, 4, 3, 2, 1]
Those copies are where the cap matters. Without Math.min(r - i, ...)z[i - l][5, 4, 4, 4, 4][4, 2, 2, 2][4, 2, 1, 0]
The line [0, 1][]
Complexity
The work is one pass over the string, plus character comparisons that only ever push the box's right end forward.
- Time: O(n) for the Z-array, O(n + m) for a search, where n is the length of the string or text and m of the pattern. Each step of the
loop that finds equal characters moveswhile right, andr never passes n. Each position also has at most one failed comparison. A search runs this on the joined string, of length n + m + 1.r - Space: O(n) for the Z-array, O(n + m) for a search. The
array has one entry per character, and for a search the joined stringz and itst array each have n + m + 1 entries.z