KMP Algorithm / LPS Array
Return the first index of needle in haystack — in O(n+m) via KMP.
Intuition
When a mismatch happens after matching k chars, naive search restarts from scratch — but we already know those k chars. The LPS array (longest proper prefix that is also a suffix) says how much of the match survives: fall back to lps[k−1] and keep going. The text pointer never moves backward.
Approach
Build LPS on the needle
lps[i] = length of the longest proper prefix of needle[0..i] that is also its suffix. Built in O(m) with the same fallback logic KMP uses.
Scan with fallback
Match text and pattern pointers; on mismatch with j > 0, set j = lps[j−1] (don't touch i). On j == 0, advance i.
Why linear
i only advances, and j falls back at most as much as it advanced → ≤ 2n pointer moves.
Solution & live demo
Edge cases
LPS = [0,1,2,0] — fallbacks skip re-matching the run of a's.
Return 0 by convention.