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 s of length n, build an array z of the same length. For every position i, z[i] is the length of the longest piece of s starting at i that is the same as the start of s. By convention z[0] = n. This array is called the Z-array. Then use it to find every position where a pattern occurs in a text.

Example 1
Input: s = "aabxaa"
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
Input: pattern = "abc", text = "aabcabcabc"
Output: [1, 4, 7]
Solution

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". At index 1 the string reads "abxaa". Its first character, "a", matches the first character of s, but then "b" meets "a", so z[1] = 1. Index 2 starts with "b" and index 3 with "x", so both get 0. Index 4 reads "aa", which is the prefix "aa", so z[4] = 2, and index 5 gets 1.

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 = 4 and right end r = 6, written [4, 6). The blue bracket marks the prefix "aa" that the box is a copy of.

The string aabxaa with its z values 6, 1, 0, 0, 2, 1. The box [4, 6) holds aa, a copy of the prefix aa, so at i = 5 the value z[1] = 1 is copied, capped at r - i = 1.

Index 5 is the second character of the box, so it sits at the same spot as index 1 in the prefix: 5 - l = 1. The text from index 5 looks like the text from index 1, at least up to the box's end. So the teal arrow copies z[1] = 1 into z[5], without comparing a single character.

The copy can only be trusted up to the box's right end, though. Past r, the string has not been compared with anything yet. That is why the label says "capped at r - i": with i = 5 as the current position, only r - i = 6 - 5 = 1 character is known to match. So the key insight is: keep the rightmost box, copy the value from the prefix for positions inside it, cap the copy at the box's end, and compare characters only beyond it.

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 i, compare s[i], s[i+1], ... with s[0], s[1], ... until they differ. For a string of n copies of "a", position i matches n - i characters, so the comparisons add up to about n²/2.

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 r covers the most of the string still to come. Whenever a new match ends past r, it becomes the box.

Filling one position

What happens at a position i? If i is inside the box, start z[i] at min(r - i, z[i - l]): the value at the same spot in the prefix, but no more than what remains of the box. If i is at or past r, start at 0. Then compare characters one by one to extend the match as far as it goes.

Each successful comparison happens at or beyond r, so it pushes the box's right end further. r never moves left and never passes n, so at most n comparisons succeed in total, and each position adds at most one that fails.

Searching for a pattern

How does an array about prefixes find a pattern? Join the pattern, a separator character such as $, and the text into one string. For Example 2 that is "abc$aabcabcabc". Now the pattern is the prefix. Any position in the text part whose z value reaches the pattern's length m starts a full copy of the pattern.

The separator must appear in neither string. Then any match starting in the text stops at the latest when it reaches $ in the prefix, so no z value there runs past m. A match start at index i of the joined string is index i - m - 1 of the text, since m pattern characters and one $ come before it.

Java Solution

The method zArray works in these steps:

  1. First, create the array z with one entry per character, return it empty for an empty string, and set z[0] to n.
  2. Start the box as empty, with l and r both 0. Then a loop moves i from 1 to the end of the string.
  3. If i is inside the box (i < r), set z[i] to Math.min(r - i, z[i - l]), the capped copy from the prefix.
  4. Still inside that loop, a second loop, a while loop, compares s.charAt(z[i]) with s.charAt(i + z[i]) and adds 1 to z[i] as long as they are equal.
  5. If the match now ends past r, it becomes the new box: l = i and r = i + z[i]. After the last position, return z.

The method search builds the joined string t = pattern + "$" + text, runs zArray on it, and adds i - m - 1 to result for every position i after the separator with z[i] >= m.

The main method runs both examples, then a string made only of "a", the string "aaab", overlapping matches, a pattern longer than the text, and an empty string.

Java
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:

Output
[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] is the one in the picture, and [1, 4, 7] lists the three places where "abc" starts in "aabcabcabc". Next, "aaaaa" gives [5, 4, 3, 2, 1]. This is where the simple way compares the most, yet the box found at index 1 already reaches the end, so every later value is a capped copy.

Those copies are where the cap matters. Without Math.min(r - i, ...), the code copies z[i - l] as it is. A run of that version prints [5, 4, 4, 4, 4] for "aaaaa" and [4, 2, 2, 2] for "aaab", where the correct line above shows [4, 2, 1, 0]. In "aaab", index 3 holds "b", so it cannot match the prefix at all.

The line [0, 1] shows that matches may overlap: "aa" starts at both index 0 and index 1 of "aaa". A pattern longer than its text gives [], and so does the empty string, whose Z-array has no entries.

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 while loop that finds equal characters moves r right, and r 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.
  • Space: O(n) for the Z-array, O(n + m) for a search. The z array has one entry per character, and for a search the joined string t and its z array each have n + m + 1 entries.

KMP searches for a pattern in the same time with a different table, and Manacher's algorithm reuses a rightmost box in the same way to find palindromes.