3.8.4 · D3String Algorithms

Worked examples — Z-algorithm — Z-array construction, O(n+m)

2,429 words11 min readBack to topic

This page is the drill hall. The parent note built the machine; here we feed it every kind of input and turn the crank by hand — every case, every degenerate string, and a real-world pattern hunt.

If a word or symbol below feels unfamiliar, it was defined in the parent — but we re-anchor the essentials so you can start from line one.

Recall Three words you must keep in your head
  • Z-array — for each starting index , the number = how many letters starting at match the very start (the prefix) of the string. If and starting at you read aab, that's a 3-letter match, so .
  • Prefix — the letters at the front of the string: a, then aa, then aab, ... The prefix is our "secret code" we keep comparing against.
  • Z-box — the rightmost stretch we already proved is a photocopy of the prefix: . l = left edge, r = right edge (both are indices). We carry this box along and reuse it.

The scenario matrix

Strings don't have "quadrants", but the Z-algorithm has exactly six behavioural cells an input can land in. Every worked example below is tagged with the cell(s) it exercises. Together they cover the whole machine.

Cell Name The situation What the code does
C1 Outside the box () No stored info at Compare from scratch; maybe open a new box
C2 Inside, mirror fits (B1) Copy free, no compare, no box change
C3 Inside, mirror hits edge (B2) Copy up to edge, then march past , grow box
C4 Degenerate all-same The -trap that the box defuses to
C5 Degenerate all-different Every ; box never opens past width 1
C6 Real / exam Pattern search, empty & length-1 edges Glue-with-separator trick, limiting inputs

Zero/limiting inputs live inside C4–C6: empty string (), one-char string (), and the separator boundary all appear below.


Example 1 — the clean warm-up (hits C1)


Example 2 — mirror fits inside (hits C2, the free copy)


Example 3 — mirror hits the edge, must march (hits C3)


Example 4 — the -trap defused (hits C4, degenerate all-same)

Figure — Z-algorithm — Z-array construction, O(n+m)

Example 5 — nothing ever matches (hits C5, degenerate all-different)


Example 6 — real-world pattern hunt (hits C6, the separator trick)

Figure — Z-algorithm — Z-array construction, O(n+m)

Example 7 — exam twist: partial vs full, and a false-positive trap (C6)



See also: Amortized Analysis (why the marching total is ), Manacher's Algorithm (the same box trick for palindromes), Suffix Array and Suffix Automaton (heavier structures for the same string questions).