KMP Failure Function Pattern Match (Python)
Match a pattern in text using KMP with a precomputed failure function for linear time matching.
Code
def kmp_search(text, pattern):
n, m = len(text), len(pattern)
if m == 0:
return [0]
fail = [0] * m
j = 0
for i in range(1, m):
while j > 0 and pattern[i] != pattern[j]:
j = fail[j - 1]
if pattern[i] == pattern[j]:
j += 1
fail[i] = j
result = []
j = 0
for i in range(n):
while j > 0 and text[i] != pattern[j]:
j = fail[j - 1]
if text[i] == pattern[j]:
j += 1
if j == m:
result.append(i - m + 1)
j = fail[j - 1]
return resultWhat the code does
KMP Failure Function Pattern Match (Python) comes down to the function kmp_search.
Iteration happens inside for i in range(1, m) — everything outside it runs once.
The result is a fresh construction, so callers can keep their originals.
Applying it
The primary signature is def kmp_search(text, pattern)
kmp_search is what another module would consume; nothing else here is load-bearing for callers.
Statements that matter
def kmp_search(text, pattern):
n, m = len(text), len(pattern)
if m == 0:
return [0]
fail = [0] * m
j = 0
for i in range(1, m):
while j > 0 and pattern[i] != pattern[j]:
j = fail[j - 1]
if pattern[i] == pattern[j]:
j += 1
fail[i] = j
Interactive Tools for This Topic
FAQ
- Does `kmp_search` modify its input?
- No — a new value is constructed for the result and the arguments are never written to.
- Is a package install part of the setup?
- No. Installation is unnecessary because only built-in APIs are used. The file defines `kmp_search` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.