Z Function
Compute Z[i] = length of the longest substring starting at i that matches a prefix of s, in O(n). Search patterns via pat$txt.
Intuition
Maintain the rightmost match window [l, r] found so far (a segment known to equal a prefix). Inside it, position i mirrors position i−l of the prefix — copy Z[i−l] for free, capped at the window edge; only extend by direct comparison past r. Every comparison pushes r right, so total work is linear.
Approach
The Z-box [l, r]
s[l..r] equals s[0..r−l]. For i inside it, the answer is already partially known from the prefix's own Z values.
Copy, cap, extend
Z[i] = min(Z[i−l], r−i+1) as a starting point; then compare characters beyond r to extend. Update [l, r] if i's match reaches further right.
Pattern search
Build Z on pat + '$ + txt: any Z value equal to len(pat) marks a full occurrence.
Solution & live demo
Edge cases
Z = [-, n−1, n−2, …] — windows chain perfectly, still linear.
'$ must not appear in either string, guaranteeing no match spans it.