Skip to content

Resource · Guide or article

Z Algorithm

Covers linear-time pattern search with the Z array, where each entry records how far the substring at that index matches the string's prefix.

Reviewed

Open the original: Z Algorithm (opens the original site in a new tab)

Practice this topicOpens the practice interviewer in Technical / coding mode; choose a question there.

Add to a roadmap

Keep this resource with a roadmap you follow. It appears as your own extra resource; the roadmap's steps don't change and it doesn't count toward your tracked steps.

Source content: English

The Z-algorithm finds occurrences of a "word" W within a main "text string" T in linear time O(|W| + |T|). Given a string S of length n, the algorithm produces an array, Z where Z[i] represents the longest substring starting from S[i] which is also a prefix of S. Finding Z for the string obtained by concatenating the word, W with a nonce character, say $ followed by the text, T, helps with pattern matching, for if there is some index i such that Z[i] equals the pattern length, then the pattern must be present at that point. While the Z array can be computed with two nested loops in O(|W| * |T|) time, the following strategy shows how to obtain it in linear time, based on the idea that as we iterate over the letters in the string (index i from 1 to n - 1), we maintain an interval [L, R] which is the interval with maximum R such that 1 ≤ L ≤ i ≤ R and S[L...R] is a prefix that is also a substring (if no such interval exists, just let L = R = - 1). For i = 1, we can simply compute L and R by comparing S[0...] to S[1...].

PrepKit overview

PrepKit editors wrote and reviewed this overview from the source repository. It is not text from the resource itself.

Suited to
The source does not state a level
Format
Reference

What it covers

  • Shows the search trick of joining pattern, a separator like $, and text, then looking for a Z value equal to the pattern length
  • Introduces the [L, R] interval that keeps the computation linear
  • Lists four Z-array examples, including aaaaaa and abababab
  • States time O(|W| + |T|) and space O(|W|)

How to use it

PrepKit study advice, not a claim made by the source.

Compute the Z arrays for the listed examples by hand, check them against the page, then code the [L, R] version and confirm it finds every pattern match.

Scope and limitations

The interval update rules are only sketched, and the Z-box diagram is an externally hosted image. Full derivations live in the linked GeeksForGeeks, YouTube and blog references.

Access and format

README on GitHub in trekhleb/javascript-algorithms (MIT). English, free to read.

Reviewed by PrepKit on Oct 2, 2026. Listing source commit: 85293e3e2b88

Evidence behind this overview
  • src/algorithms/string/z-algorithm/README.md

Pages that include this

Get the PrepKit newsletter

Optional. You don't need it to use PrepKit.

How we handle your email