allizwell.jobsdoor360.in

Z Algorithm

Data Structures and Algorithms / Strings / Z Algorithm

Z Algorithm in Data Structures and Algorithms

The Z Algorithm is an efficient string matching algorithm used to find occurrences of a pattern inside a text. It calculates a Z-array that stores the length of the longest substring starting at each position that matches the prefix of the complete string. The algorithm solves pattern matching problems in linear time, making it useful for processing large strings efficiently.

1. What is the Z Algorithm?

The Z Algorithm is a linear-time string processing technique. It calculates an array called the Z-array for a given string.

Each element of the Z-array represents the length of the longest substring starting at that position that matches the prefix of the original string.

In simple terms, the algorithm checks how many characters from a particular position match the beginning of the string.

Important: By convention, Z[0] is usually considered 0 because the entire string trivially matches its own prefix. Some implementations use the string length at this position instead.

2. Understanding the Z-array

Consider the following string:

String:  a a b a a b a

The prefix of this string begins with aababa. The Z-array tells us how many characters match this prefix when comparing it with the substring starting at each position.

Example

Consider the string:

str = "aabxaab"

The Z-array is:

Index:  0 1 2 3 4 5 6
String: a a b x a a b
Z:      0 1 0 0 3 1 0

Explanation:

  • Z[1] = 1: The substring "abxaab" starts with "a", matching one character of the prefix.
  • Z[2] = 0: The substring starts with "b", which does not match the prefix character "a".
  • Z[3] = 0: The substring starts with "x", which does not match the prefix.
  • Z[4] = 3: The substring "aab" matches the prefix "aab" for three characters.
  • Z[5] = 1: Only the first character matches.
  • Z[6] = 0: The character "b" does not match the prefix.

3. How Does the Z Algorithm Work?

The efficient Z Algorithm maintains a range called the Z-box. It is represented by two variables:

  • L: The left boundary of the current matching range.
  • R: The right boundary of the current matching range.

The substring from L to R matches a prefix of the original string. This information helps avoid unnecessary character comparisons.

Main Steps

  1. Initialize the Z-array with zeros.
  2. Start processing the string from index 1.
  3. If the current index is outside the existing Z-box, compare characters directly with the prefix.
  4. If the current index is inside the Z-box, reuse previously calculated Z-values where possible.
  5. Extend the matching range whenever additional characters match.
  6. Update L and R when a new matching range extends farther to the right.
  7. Continue until every position has been processed.
The main advantage of the Z Algorithm is that it avoids repeatedly comparing characters that have already been matched.

4. Z Algorithm Implementation in C++

The following function calculates the Z-array using the efficient linear-time approach.

#include <iostream>
#include <vector>
#include <string>
using namespace std;

vector<int> calculateZ(string s) {

    int n = s.length();

    vector<int> z(n, 0);

    int L = 0, R = 0;

    for (int i = 1; i < n; i++) {

        if (i <= R) {
            z[i] = min(R - i + 1, z[i - L]);
        }

        while (i + z[i] < n &&
               s[z[i]] == s[i + z[i]]) {

            z[i]++;
        }

        if (i + z[i] - 1 > R) {

            L = i;
            R = i + z[i] - 1;
        }
    }

    return z;
}

int main() {

    string s = "aabxaab";

    vector<int> z = calculateZ(s);

    cout << "Z-array: ";

    for (int value : z) {
        cout << value << " ";
    }

    return 0;
}

Output

Z-array: 0 1 0 0 3 1 0

5. Understanding the Code

Step 1: Initialize the Z-array

vector<int> z(n, 0);

We create an integer array of size n and initialize every element with zero. It will store the matching prefix length for each index.

Step 2: Initialize the Z-box

int L = 0, R = 0;

L and R represent the boundaries of the current Z-box. Initially, no useful matching range has been established.

Step 3: Reuse Previous Z-values

if (i <= R) {
    z[i] = min(R - i + 1, z[i - L]);
}

If the current index lies inside the existing Z-box, we can use previously calculated information to initialize its Z-value. This reduces unnecessary comparisons.

Step 4: Extend the Match

while (i + z[i] < n &&
       s[z[i]] == s[i + z[i]]) {

    z[i]++;
}

We compare characters from the beginning of the string with characters starting at the current index. Every successful comparison increases the Z-value.

Step 5: Update the Z-box

if (i + z[i] - 1 > R) {

    L = i;
    R = i + z[i] - 1;
}

If the newly discovered matching substring extends beyond the current right boundary, we update the Z-box.

6. Dry Run of the Z Algorithm

Let us calculate the Z-array for the string:

s = "aabxaab"
Index Substring Matching Prefix Z-value
0 aabxaab Conventionally ignored 0
1 abxaab a 1
2 bxaab No match 0
3 xaab No match 0
4 aab aab 3
5 ab a 1
6 b No match 0

Final Z-array:

Z = [0, 1, 0, 0, 3, 1, 0]

7. Pattern Matching Using the Z Algorithm

One important application of the Z Algorithm is finding all occurrences of a pattern inside a text.

We combine the pattern and text into a new string using a special separator that does not occur in either input:

combined = pattern + "$" + text

We then calculate the Z-array for this combined string. Whenever a Z-value is equal to the length of the pattern, a complete occurrence of the pattern has been found in the text.

C++ Code for Pattern Matching

#include <iostream>
#include <vector>
#include <string>
using namespace std;

vector<int> calculateZ(string s) {

    int n = s.length();

    vector<int> z(n, 0);

    int L = 0, R = 0;

    for (int i = 1; i < n; i++) {

        if (i <= R) {
            z[i] = min(R - i + 1, z[i - L]);
        }

        while (i + z[i] < n &&
               s[z[i]] == s[i + z[i]]) {
            z[i]++;
        }

        if (i + z[i] - 1 > R) {
            L = i;
            R = i + z[i] - 1;
        }
    }

    return z;
}

void searchPattern(string text, string pattern) {

    if (pattern.empty()) {
        cout << "Empty pattern is not supported.";
        return;
    }

    string combined = pattern + "$" + text;

    vector<int> z = calculateZ(combined);

    int m = pattern.length();

    cout << "Pattern found at positions: ";

    bool found = false;

    for (int i = m + 1; i < combined.length(); i++) {

        if (z[i] == m) {

            cout << i - m - 1 << " ";

            found = true;
        }
    }

    if (!found) {
        cout << "Not found";
    }
}

int main() {

    string text = "ababcabcab";
    string pattern = "abc";

    searchPattern(text, pattern);

    return 0;
}

Output

Pattern found at positions: 2 5

Note: The positions are zero-based indexes. The separator '$' must not appear in either the pattern or text. If that cannot be guaranteed, use a separator that is absent from both strings.

8. Time and Space Complexity

The Z Algorithm processes each character efficiently by reusing previously calculated matching information.

Operation Time Complexity Explanation
Z-array construction O(n) Each character is processed efficiently using the Z-box.
Pattern matching O(n + m) The combined string has length n + m + 1.
Space complexity O(n) The Z-array stores one integer for each character.

Here, n represents the length of the string for Z-array construction. For pattern matching, n is the text length and m is the pattern length.

9. Advantages of the Z Algorithm

  • It performs string processing in linear time.
  • It avoids many repeated character comparisons.
  • It is useful for finding pattern occurrences in a text.
  • It can identify repeated prefixes and matching substrings.
  • It is suitable for large input strings.
  • Its implementation uses a simple Z-array and two boundary variables.

10. Limitations of the Z Algorithm

  • It requires additional memory for the Z-array.
  • It may be less familiar to beginners than straightforward string matching.
  • Pattern matching with a combined string requires a separator that does not create false matches.
  • It is designed for prefix-based string comparisons, so other problems may require different techniques.

11. Applications of the Z Algorithm

  • Pattern Matching: Finding all occurrences of a pattern in a text.
  • Prefix Matching: Finding how much a substring matches the beginning of a string.
  • Repeated Substrings: Identifying repeated prefix structures.
  • String Analysis: Studying similarities between different portions of a string.
  • Competitive Programming: Solving efficient string-processing problems.
  • Text Processing: Supporting applications that need fast substring matching.

12. Z Algorithm vs KMP Algorithm

Both the Z Algorithm and KMP Algorithm solve string matching problems in linear time, but they use different approaches.

Feature Z Algorithm KMP Algorithm
Main Structure Z-array LPS array
Core Idea Prefix matching at every position Longest proper prefix that is also a suffix
Time Complexity O(n + m) for pattern matching O(n + m) for pattern matching
Space Complexity O(n + m) for combined-string matching O(m) for the LPS array
Typical Use Prefix-based string analysis and pattern matching Efficient pattern searching using prefix-suffix information

13. Common Mistakes to Avoid

  • Confusing the Z-value with the actual character index.
  • Forgetting that Z[0] is conventionally set to zero.
  • Using incorrect Z-box boundaries.
  • Accessing characters beyond the string length.
  • Forgetting to update L and R after finding a longer match.
  • Using a separator that already exists in the pattern or text.
  • Confusing zero-based pattern positions with one-based positions.

14. Practice Questions

Basic Questions

  1. What is the Z Algorithm?
  2. What is a Z-array?
  3. What does Z[i] represent?
  4. What is a Z-box?
  5. Why do we maintain L and R?

Intermediate Questions

  1. Calculate the Z-array for the string "aaaaa".
  2. Calculate the Z-array for the string "abacaba".
  3. Find all occurrences of pattern "aba" in text "ababaaba".
  4. Explain how previous Z-values help reduce comparisons.
  5. Compare the Z Algorithm with the KMP Algorithm.

Programming Practice

  1. Write a C++ program to calculate the Z-array of a given string.
  2. Write a program to find all occurrences of a pattern using the Z Algorithm.
  3. Find the longest prefix that also appears as a substring at another position.
  4. Count how many times a given pattern appears in a text.
  5. Use the Z Algorithm to identify prefix matches at every position.

15. Key Takeaways

  • The Z Algorithm is an efficient string-processing algorithm.
  • It constructs a Z-array containing prefix-match lengths.
  • The Z-box is represented using L and R.
  • It uses previously calculated values to avoid repeated comparisons.
  • Its Z-array construction takes O(n) time.
  • It can perform pattern matching in O(n + m) time.
  • It is useful in competitive programming and advanced string problems.
Module 05 Completed! You have now covered the major string concepts and algorithms, including string traversal, reversal, palindrome problems, anagrams, frequency counting, pattern matching, KMP, Rabin-Karp, and the Z Algorithm. You are ready to move on to the next DSA module.
Scroll to Top