Hints — p93 Implement strStr / KMP
-
Naive O(n·m) is the baseline. KMP gets O(n+m) by never restarting
iin the haystack. -
Precompute lps (longest proper prefix-suffix):
lps[i]= length of longest proper prefix ofneedle[0..i]that’s also a suffix. -
Building lps: maintain
length= previous longest. On match,length += 1, lps[i] = length, i++. On mismatch, fall back vialength = lps[length-1](without advancing i), unlesslength == 0(thenlps[i] = 0, i++). -
Match loop: walk
ithrough haystack andjthrough needle. On mismatch withj > 0, setj = lps[j-1]; elsei++. Onj == m, found match ati - m. -
Amortized linear:
istrictly increases;jincreases at most n times, decreases at most n times. Total O(n+m).
If stuck: see solution.py.