Python Implementation of the KMP Algorithm

suggest change

The haystack is the text to search, and the needle is the pattern to find.

Building the longest-prefix-suffix (LPS) table takes O(m) time, and searching takes O(n) time. The overall time complexity is O(n + m), with O(m) auxiliary space.

This implementation follows the convention of str.find: an empty needle matches at index 0, and a missing needle returns -1.

def build_lps(pattern: str) -> list[int]:
    lps = [0] * len(pattern)
    prefix_length = 0

    for index in range(1, len(pattern)):
        while prefix_length and pattern[index] != pattern[prefix_length]:
            prefix_length = lps[prefix_length - 1]
        if pattern[index] == pattern[prefix_length]:
            prefix_length += 1
            lps[index] = prefix_length
    return lps


def kmp_search(text: str, pattern: str) -> int:
    if not pattern:
        return 0

    lps = build_lps(pattern)
    matched = 0
    for index, character in enumerate(text):
        while matched and character != pattern[matched]:
            matched = lps[matched - 1]
        if character == pattern[matched]:
            matched += 1
            if matched == len(pattern):
                return index - matched + 1
    return -1


print(kmp_search("abxabcabcaby", "abcaby"))
6

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents