Problem 66 · Strings & Tries
strStr via KMP (and Rabin-Karp)
01Problem
Return the index of the first occurrence of needle in haystack, or -1. Achieve linear time.
02Key insight
KMP precomputes the longest proper prefix-that-is-also-suffix (LPS) for the needle so mismatches fall back without re-scanning haystack, giving O(n+m) worst case. Rabin-Karp gets expected linear time with a rolling hash and extends to multi-pattern search.
03Solution
Try it first.
TimeO(n + m)
SpaceO(m)
tests.py · 2 passing
tests.pypython3 lines
assert build_lps("aabaaab") == [0, 1, 0, 1, 2, 2, 3]
for h, n in [("sadbutsad", "sad"), ("leetcode", "leeto"), ("aaaaab", "aab"), ("abc", ""), ("a", "ab")]:
assert str_str(h, n) == rabin_karp(h, n) == h.find(n)04Staff-level follow-up
Searching thousands of patterns over a log stream? Aho-Corasick (trie + failure links, KMP generalized) gives O(n + total pattern length + matches) in one pass.