Python String Z-Transform: What It Is & How to Use It

How-to basics · Updated November 23, 2026

Python strings do not have a built-in “z-transform” method, but the term usually refers to two distinct things: the Z algorithm for pattern matching (which computes a Z-array for a string) and the Z-transform from signal processing (which Python implements via libraries like NumPy or SciPy). This article covers both, focusing on the string Z-algorithm because that is what most programmers mean when they search for “Python string z transform.”

What Is the Z-Algorithm?

The Z-algorithm is a linear-time string matching technique that preprocesses a string S to produce an array Z, where Z[i] is the length of the longest substring starting at position i that matches the prefix of S. For example, for S = "ababab", Z[2] = 4 because the substring starting at index 2 ("abab") matches the first four characters. The algorithm runs in O(n) time, making it faster than naive O(n²) approaches for many pattern matching tasks.

It is not a built-in Python function. You implement it yourself or use a library like pydivsufsort (for suffix arrays) or z_algorithm from some third-party packages, but the standard library does not include it. The most common use is to find all occurrences of a pattern P in a text T by concatenating P + '$' + T and computing the Z-array.

How the Z-Array Works (Step by Step)

Given a string S of length n, the algorithm maintains an interval [L, R] that is the rightmost segment that matches the prefix. Initially L = R = 0. For each position i from 1 to n-1:

  • If i > R, compare S[i:] with the prefix character by character until mismatch. Set Z[i] to the match length, and update L = i, R = i + Z[i] - 1.
  • If i <= R, then Z[i] can be at least min(R - i + 1, Z[i - L]). Use that as a starting point, then extend further if possible, updating L and R if the extension goes beyond R.

This clever reuse of previously computed values is what gives linear time. The algorithm never compares a character more than twice, so total work is O(n).

Implementing the Z-Algorithm in Python

Here is a clean, correct implementation. Save this as a function and reuse it:

def z_algorithm(s):
    n = len(s)
    z = [0] * n
    l, r = 0, 0
    for i in range(1, n):
        if i <= r:
            z[i] = min(r - i + 1, z[i - l])
        while i + z[i] < n and s[z[i]] == s[i + z[i]]:
            z[i] += 1
        if i + z[i] - 1 > r:
            l, r = i, i + z[i] - 1
    z[0] = n  # convention: Z[0] is often set to n or 0
    return z

Test it: z_algorithm("aaaa") returns [4, 3, 2, 1]. z_algorithm("abab") returns [4, 0, 2, 0]. Note that many implementations set Z[0] = 0 (since the whole string matches itself trivially), but setting it to n is also common. Choose one convention and document it.

Using Z-Array for Pattern Matching

To find all occurrences of pattern P in text T, concatenate P + '$' + T where $ is a character not in either string. Compute the Z-array. Every index i where Z[i] == len(P) indicates a match starting at position i - len(P) - 1 in T. Example:

def find_pattern(text, pattern):
    combined = pattern + '$' + text
    z = z_algorithm(combined)
    m = len(pattern)
    matches = []
    for i in range(m + 1, len(combined)):
        if z[i] == m:
            matches.append(i - m - 1)
    return matches

print(find_pattern("abcabcabc", "abc"))  # [0, 3, 6]

This runs in O(len(T) + len(P)) time and uses O(len(T) + len(P)) extra space. It is a solid alternative to KMP (Knuth-Morris-Pratt) and often simpler to implement correctly.

Z-Transform in Signal Processing (NumPy/SciPy)

If you meant the mathematical Z-transform (discrete-time signal analysis), Python does not have a direct “ztransform” function, but you can compute it symbolically with sympy or numerically with scipy.signal. For example, scipy.signal.TransferFunction represents a system in the Z-domain. To compute the Z-transform of a sequence, you typically use the formula X(z) = sum(x[n] * z**(-n)). For finite sequences, you can evaluate that polynomial manually. For symbolic work, SymPy’s sympy.simplify and sympy.summation help, but there is no one-liner. Most engineers use the Z-transform for filter design, which scipy.signal handles via tf2zpk or freqz.

Choosing Between Z-Algorithm and Other Methods

For pattern matching, the Z-algorithm is often the best choice when you need all occurrences and the pattern is known in advance. Compare:

  • Naive search: O(n*m) worst case, but fine for short strings.
  • KMP: O(n+m) with a prefix function; slightly more complex to implement but no separator character needed.
  • Boyer-Moore: Often faster in practice for long patterns, but worst-case O(n*m).
  • Z-algorithm: O(n+m) and very easy to remember, but requires a unique separator (or careful handling of overlapping matches without it).
  • Regular expressions: For simple patterns, re.finditer is fastest to write, but the Z-algorithm is faster for very large texts with many matches.

If you are doing repeated searches on the same text with different patterns, consider building a suffix array or suffix tree instead, which allows O(m + log n) per query after O(n log n) preprocessing.

Common Pitfalls and Edge Cases

  • Z[0] convention: Some code expects Z[0] to be 0, others n. In pattern matching, you ignore index 0 anyway, so it rarely matters, but be consistent.
  • Separator collision: If your pattern or text contains the separator character (like $), matches break. Use a character that cannot appear, or use a list of integers instead of a string.
  • Empty pattern: If pattern is empty, the algorithm returns matches at every index. Decide if that is desired.
  • Unicode: The algorithm works on any sequence of comparable elements, including lists of integers or Unicode characters, as long as you use a separator that is not in the data.
  • Memory: The Z-array uses O(n) memory. For very large strings (gigabytes), this can be a problem; consider streaming or suffix automata.

Frequently Asked Questions

Is there a built-in Python function for the Z-transform of a string? No. The standard library has no Z-algorithm or Z-transform. You must implement it (as above) or use third-party libraries. For signal processing, use scipy.signal or sympy.

What is the difference between Z-algorithm and KMP? Both find patterns in linear time. KMP uses a prefix function (pi) computed on the pattern, while Z-algorithm computes a Z-array on the combined string. Z-algorithm is often easier to code from memory, but KMP avoids the extra concatenation and separator.

Can I use the Z-algorithm for finding the longest repeated substring? Yes. Compute the Z-array for the string, and the maximum Z[i] where i is not the start gives the longest prefix that repeats somewhere. But for the longest repeated substring anywhere (not just prefix), you need suffix arrays or dynamic programming.

Does the Z-algorithm work with binary strings or lists? Yes, as long as you can compare elements. For lists, use a sentinel value that is not in the list, like None or -1.

What is the time complexity of the Z-algorithm? O(n) for computing the Z-array, and O(n+m) for pattern matching. This is optimal for single-pattern matching.

Is the Z-transform the same as the Laplace transform? No. The Z-transform is the discrete-time equivalent of the Laplace transform. It maps a discrete sequence to a complex function of z. Python does not have a one-line function for it, but you can compute it via summation or use control system libraries.

Performance and Optimization Tips

For very long strings (millions of characters), the pure Python loop above may be slow. Consider using numpy with vectorized comparisons for short patterns, or write a C extension. For most practical uses, the pure Python version is fine. If you need to search many patterns in one text, preprocess the text with a suffix array (using pydivsufsort) or a suffix automaton. The Z-algorithm is also useful for computing the “longest prefix which is also a suffix” for each position, which appears in string compression algorithms.

Memory optimization: instead of storing the entire Z-array, you can process matches on the fly if you only need the first few matches. But for all matches, you need the array or a generator that yields matches as they are found (which still requires O(n) time but O(1) extra space if you discard Z values).

Related

Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.

More in How-to basics

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.