Description
Replace the current naive O(n×m) search in index_of with the Knuth-Morris-Pratt (KMP) algorithm, which runs in O(n+m) time by preprocessing the pattern to avoid redundant comparisons.
Current complexity
Naive: O(n × m) — n = target length, m = fragment length
Target complexity
KMP: O(n + m) — linear time
How KMP works
- Build a failure function (partial match table) from the pattern — O(m)
- Use it to skip positions in the target that are guaranteed not to match — O(n)
References
Description
Replace the current naive O(n×m) search in
index_ofwith the Knuth-Morris-Pratt (KMP) algorithm, which runs in O(n+m) time by preprocessing the pattern to avoid redundant comparisons.Current complexity
Target complexity
How KMP works
References