GeeksforGeeks Medium

Z Function

Z Function is a GFG problem (Medium). For a string s of length n, build an array Z where Z[i] is the length of the longest substring starting at index i that is also a prefix of s.

  • Z[0] is set to 0 by convention, because the whole string trivially matches itself.
  • The follow-up is pattern search: return every 0-based index where pat occurs in txt.
  • With n up to 10⁵, checking each index from scratch is too slow on strings like "aaaa…a". The target is O(n).
Constraints
  • 1 <= s.length <= 10⁵
  • Pattern search: 1 <= pat.length <= txt.length, lowercase letters only
stringz-algorithmpattern-matching
Open on GeeksforGeeks ↗
02

Intuition

Comparing every index against the prefix from scratch repeats work. Once you find that s[l..r] equals s[0..r−l], every index inside that stretch is a copy of an index near the front, so its answer is mostly known already.

  • The Z-box: keep [l, r], the match that reaches furthest right so far.
  • The mirror: for i inside the box, index i − l sits at the same place in the prefix, so Z[i] starts at min(Z[i − l], r − i + 1).
  • The extension: only letters past r are compared directly, and each successful comparison pushes r right. Since r only grows, the whole run does O(n) comparisons.
How to spot this pattern

Any question of the form "how far does the text starting here agree with the start of the string?" is a Z array question. Exact pattern search, finding the shortest period of a string and counting how often prefixes repeat all reduce to it.

03

Approach

Try it first

Before reading on, write the Z array of "aabaaab" by hand, comparing each index from scratch. Then look at index 4: was there any comparison you had already done while working out index 3?

1

Start with an empty box

Create z filled with zeros and set l = r = 0. With r = 0, no index from 1 onward is inside the box, so the first index is always compared from scratch.

2

Copy from the mirror when inside the box

For each i from 1, if i <= r, set z[i] = min(z[i - l], r - i + 1). The box guarantees letters up to r match the prefix, but says nothing past r, so the copied value can never reach beyond the box.

3

Extend by direct comparison

While i + z[i] < n and s[z[i]] == s[i + z[i]], add 1 to z[i]. This checks only letters the box did not cover, and stops at the first mismatch or the end of the string.

4

Move the box when the match reaches further

If i + z[i] - 1 > r, set l = i and r = i + z[i] - 1. Keeping the box that reaches furthest right lets later indices copy as much as possible without comparing.

5

Search a pattern with a separator

Build s = pat + "$" + txt and its Z array. Any index with z[i] == len(pat) starts a full copy of the pattern, at text index i - len(pat) - 1. The $ appears in neither string, so no value can exceed the pattern length.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def zFunction(self, s: str) -> list[int]:
▶3 n = len(s)
▶4 z = [0] * n
▶5 l = r = 0
▶6 for i in range(1, n):
▶7 if i <= r:
▶8 z[i] = min(z[i - l], r - i + 1)
▶9 while i + z[i] < n and s[z[i]] == s[i + z[i]]:
▶10 z[i] += 1
▶11 if i + z[i] - 1 > r:
▶12 l, r = i, i + z[i] - 1
▶13 return z
▶14 
▶15 def search(self, pat: str, txt: str) -> list[int]:
▶16 s = pat + "$" + txt
▶17 z = self.zFunction(s)
▶18 m = len(pat)
▶19 return [i - m - 1 for i in range(m + 1, len(s)) if z[i] == m]
stringa0a1b2a3a4a5b6z values0this check=Z of spot 0 is left as 0
l0
r0
Spot 0 is the whole string, so its Z value means nothing and is left as 0. The Z-box, the rightmost stretch known to equal the start of the string, is empty for now.
stringa0a1b2a3a4a5b6z values00this check=spot 1 is past the box → start at 0
i1
r0
start0
No Z-box exists yet, so nothing earlier says anything about spot 1. Start its Z value at 0 and compare letters directly.
stringa0a1b2a3a4a5b6z values01this checka=aspot 0spot 1a matches a → 1 agree
i1
Z1
box0–0
Spot 1 matches spot 0 of the prefix, so 1 letters from spot 1 now equal the start.
stringZ-boxa0a1b2a3a4a5b6z values01this checka≠bspot 1spot 2b differs from a → stop at 1, box 1–1
i1
Z1
box1–1
Spot 2 (b) differs from spot 1 (a), so the run from spot 1 stops at 1. It reaches past the old box end, so the box moves to 1–1; later spots inside it can copy from the prefix.
stringZ-boxa0a1b2a3a4a5b6z values010this check=spot 2 is past the box → start at 0
i2
r1
start0
Spot 2 is past the box end 1, so no earlier work covers it. Start its Z value at 0 and compare letters directly.
stringZ-boxa0a1b2a3a4a5b6z values010this checka≠bspot 0spot 2b differs from a → stop at 0
i2
Z0
box1–1
Spot 2 (b) differs from spot 0 (a), so the run from spot 2 stops at 0.
stringZ-boxa0a1b2a3a4a5b6z values0100this check=spot 3 is past the box → start at 0
i3
r1
start0
Spot 3 is past the box end 1, so no earlier work covers it. Start its Z value at 0 and compare letters directly.
stringZ-boxa0a1b2a3a4a5b6z values0101this checka=aspot 0spot 3a matches a → 1 agree
i3
Z1
box1–1
Spot 3 matches spot 0 of the prefix, so 1 letters from spot 3 now equal the start.
stringZ-boxa0a1b2a3a4a5b6z values0102this checka=aspot 1spot 4a matches a → 2 agree
i3
Z2
box1–1
Spot 4 matches spot 1 of the prefix, so 2 letters from spot 3 now equal the start.
stringZ-boxa0a1b2a3a4a5b6z values0102this checkb≠aspot 2spot 5a differs from b → stop at 2, box 3–4
i3
Z2
box3–4
Spot 5 (a) differs from spot 2 (b), so the run from spot 3 stops at 2. It reaches past the old box end, so the box moves to 3–4; later spots inside it can copy from the prefix.
stringZ-boxa0a1b2a3a4a5b6same letters as the boxz values01021this check1min1=1mirrorroomstartspot 4 is inside the box → start at 1
i4
mirror1
start1
Spot 4 is inside the box 3–4, and the box spells the same letters as spots 0–1. So spot 4 looks like spot 1, whose Z value is 1. 1 fits inside the box (room 1), so it is known for free. Letters past that still get checked one by one.
stringZ-boxa0a1b2a3a4a5b6z values01022this checka=aspot 1spot 5a matches a → 2 agree
i4
Z2
box3–4
Spot 5 matches spot 1 of the prefix, so 2 letters from spot 4 now equal the start.
stringZ-boxa0a1b2a3a4a5b6z values01023this checkb=bspot 2spot 6b matches b → 3 agree, string ends, box 4–6
i4
Z3
box4–6
Spot 6 matches spot 2 of the prefix, so 3 letters from spot 4 now equal the start. The string ends here, so the run stops. It reaches past the old box end, so the box moves to 4–6; later spots inside it can copy from the prefix.
stringZ-boxa0a1b2a3a4a5b6same letters as the boxz values010231this check1min2=1mirrorroomstartspot 5 is inside the box → start at 1
i5
mirror1
start1
Spot 5 is inside the box 4–6, and the box spells the same letters as spots 0–2. So spot 5 looks like spot 1, whose Z value is 1. 1 fits inside the box (room 2), so it is known for free. Letters past that still get checked one by one.
stringZ-boxa0a1b2a3a4a5b6z values010231this checka≠bspot 1spot 6b differs from a → stop at 1
i5
Z1
box4–6
Spot 6 (b) differs from spot 1 (a), so the run from spot 5 stops at 1.
stringZ-boxa0a1b2a3a4a5b6same letters as the boxz values0102310this check0min1=0mirrorroomstartspot 6 is inside the box → start at 0
i6
mirror2
start0
Spot 6 is inside the box 4–6, and the box spells the same letters as spots 0–2. So spot 6 looks like spot 2, whose Z value is 0. 0 fits inside the box (room 1), so it is known for free. Letters past that still get checked one by one.
stringZ-boxa0a1b2a3a4a5b6z values0102310this checka≠bspot 0spot 6b differs from a → stop at 0
i6
Z0
box4–6
Spot 6 (b) differs from spot 0 (a), so the run from spot 6 stops at 0.
stringZ-boxa0a1b2a3a4a5b6z values0102310this check=done: every Z value is known
Z0, 1, 0, 2, 3, 1, 0
All Z values are known. Each successful comparison pushed the box end right, and the box end never moves back, so the whole run made fewer than 2n comparisons.
05

Common pitfalls

Copying the mirror value without the cap

✗ Wrong
if i <= r:
    z[i] = z[i - l]
✓ Right
if i <= r:
    z[i] = min(z[i - l], r - i + 1)

For "aaaab" the box after index 1 is [1, 3] and z[1] = 3. At index 2 the uncapped copy gives 3, claiming "aab" equals "aaa". The cap gives 2, and the comparison of a with b then correctly stops there.

Moving the box on every index

✗ Wrong
l, r = i, i + z[i] - 1
✓ Right
if i + z[i] - 1 > r:
    l, r = i, i + z[i] - 1

A short match found later pulls r back to the left. In "aabaaab" the box [4, 6] shrinks to [5, 5] at index 5, so index 6 loses its free start and is compared from scratch. The values stay correct, but the O(n) bound relies on r only moving right.

Joining pattern and text without a separator

✗ Wrong
s = pat + txt
✓ Right
s = pat + "$" + txt

With pat = "aa" and txt = "aaa", the joined "aaaaa" has z[2] = 3: the match runs on past the pattern length, so z[i] == m misses the occurrence at text index 0. The $ matches no letter, so no value can go above m.

06

Edge cases

Every letter the same, such as "aaaaa"

Index 1 compares its way to the end, and every later index copies its whole answer from the mirror. Z is [0, 4, 3, 2, 1] after only a handful of comparisons.

Pattern occurrences that overlap, such as "aa" in "baaa"

Z values at consecutive indices can both equal the pattern length, so both start positions, 1 and 2, are reported.

07

Complexity

Time
O(n)
Space
O(n)
Each successful comparison moves r one step right and r never decreases, so there are at most n of them. Each index adds at most one failed comparison. Pattern search runs on a string of length m + n + 1, so it is O(m + n).
08

Z array, KMP and a plain scan

All three find every copy of a pattern. They differ in what they compute first and what they keep in memory.

MethodComputed firstTimeExtra spaceBest when
Z array (this page)Z values of pat + "$" + txtO(n + m)O(n + m)you also want prefix-match lengths at every index
KMP searcha border table of the pattern onlyO(n + m)O(m)the text arrives as a stream
Plain scannothingO(n·m) worst caseO(1)the pattern is short and the input is friendly
09

Z Function FAQ

How is the Z array different from the KMP prefix table?

Both describe how a string overlaps its own start. Z looks forward: from index i, how far does the text match the prefix? The prefix table looks backward: which prefix ends at index i? Each can be converted into the other in O(n).

Why is index 0 set to 0?

The substring starting at 0 is the whole string, which matches itself for all n letters. That value tells you nothing, so most write-ups store 0 (some store n). The algorithm never reads z[0], because the box always starts at l >= 1.

Can the Z array find the shortest repeating unit of a string?

Yes. The smallest p that divides n and has p + z[p] == n is the period, since the string then equals itself shifted by p. If no such p exists, the string does not repeat.