Python 3D Academyবাংলা

Finding a word in a text: rolling hash and KMP

🌍 In real life. Press Ctrl+F in a 300-page PDF and type a name: the answer appears at once. The plain way would be to line the name up under the text at every position and compare letter by letter. For a text of n letters and a word of m letters that is up to n × m comparisons, and most of them repeat work already done.

Two classic ideas avoid that waste. Rabin–Karp gives every window of text a number, a fingerprint, that can be updated in one step as the window slides, and only compares letters when the fingerprints agree. KMP (Knuth–Morris–Pratt) never moves backwards in the text: after a mismatch it already knows how much of what it matched can still count.

The idea in one sentence: Rabin–Karp slides a window across the text, updating the window's hash in O(1) per step and checking letters only when it equals the pattern's hash; KMP builds a table that says, for each prefix of the pattern, the longest part that is both its start and its end, so after a mismatch the search continues without re-reading the text.

Its words:

  • pattern and text: the word you look for, and where you look
  • rolling hash: a window's fingerprint, updated by taking out the letter that leaves and adding the one that enters
  • collision: two different windows with the same hash, which is why letters are still compared on a match
  • border: a part of a string that is both a prefix and a suffix, like ab in abab
  • failure table (fail[i]): the length of the longest proper border of pat[:i + 1]

Step by step, the failure table of ababc:

  1. a: no proper border: 0. ab: none: 0.
  2. aba: a is both start and end: 1.
  3. abab: ab is both: 2.
  4. ababc: c doesn't continue aba, so fall back to the border of ab, which is 0; c doesn't continue that either: 0.

Watch the table being built. k is the length of the border being extended:

Searching with the table (KMP). Walk the text once with k, how much of the pattern matches so far. If the next text letter equals pat[k], k grows; at a mismatch, k = fail[k - 1] keeps the longest border of what matched and tries again; when k reaches the pattern's length, a match ends here, and k = fail[k - 1] lets overlapping matches be found too.

Why KMP is O(n + m). Building the table is O(m). In the search, the text index only moves forward, n steps; k goes up by at most 1 per letter, and every fall back lowers it, so the fall backs add up to at most n too. In total O(n + m), however unlucky the text.

Rabin–Karp's rolling hash. Treat a window of m letters as an m-digit number in base 256 (using ord), kept small with % mod. Sliding one step: take away the leaving letter times 256^(m−1), multiply by 256, add the entering letter. One O(1) update per step, so the search is O(n + m) on average. Equal hashes can still be a collision, so letters are compared to be sure; with a bad modulus or a nasty text that can happen a lot, which is the worst case, O(n × m).

In Python text.find(pat) and pat in text are already fast, built into the language. Write these yourself in interviews, and when you need the ideas: rolling hashes for comparing many windows (duplicate passages), the failure table for problems about repeated prefixes (LeetCode 28, 459, 1392).

def failure(pat):
    fail, k = [0] * len(pat), 0
    for i in range(1, len(pat)):
        while k > 0 and pat[i] != pat[k]:
            k = fail[k - 1]
        if pat[i] == pat[k]:
            k += 1
        fail[i] = k
    return fail


def kmp(text, pat):
    fail, k, found = failure(pat), 0, []
    for i, ch in enumerate(text):
        while k > 0 and ch != pat[k]:
            k = fail[k - 1]
        if ch == pat[k]:
            k += 1
        if k == len(pat):
            found.append(i - k + 1)
            k = fail[k - 1]
    return found


def rabin_karp(text, pat, base=256, mod=1_000_003):
    n, m = len(text), len(pat)
    if m > n:
        return []
    high = pow(base, m - 1, mod)
    want = got = 0
    for i in range(m):
        want = (want * base + ord(pat[i])) % mod
        got = (got * base + ord(text[i])) % mod
    found = []
    for start in range(n - m + 1):
        if got == want and text[start:start + m] == pat:
            found.append(start)
        if start + m < n:
            got = ((got - ord(text[start]) * high) * base + ord(text[start + m])) % mod
    return found


song = "ababcabababc"
print(kmp(song, "ababc"), rabin_karp(song, "ababc"))
print(kmp("aaaa", "aa"), song.find("ababc"))
Both find the matches at 0 and 7. kmp("aaaa", "aa") finds the overlapping ones too: 0, 1 and 2.

Mistakes and edge cases.

  • Trusting a hash match. Two different windows can share a hash; always compare the letters before reporting a match.
  • Forgetting % mod. Without it the window's number has m digits in base 256, so every update works on a huge integer and the O(1) step isn't O(1) any more.
  • Starting the table at i = 0. A string is always its own border, so fail[0] must stay 0; the loop starts at 1.
  • Resetting k to 0 after a mismatch. That is the plain search again: for aaab in aaaaab it would miss matches or re-read letters. Fall back to fail[k - 1].
  • An empty pattern. pat[k] raises IndexError: string index out of range; decide first what an empty pattern should mean (Python's find answers 0).

Quiz

  1. What does this print?

    def failure(pat):
        fail, k = [0] * len(pat), 0
        for i in range(1, len(pat)):
            while k > 0 and pat[i] != pat[k]:
                k = fail[k - 1]
            if pat[i] == pat[k]:
                k += 1
            fail[i] = k
        return fail
    
    
    print(failure("aabaa"))
  2. Rabin–Karp finds a window whose hash equals the pattern's hash. What must it do next?

    • Compare the letters, because different windows can share a hash
    • Report a match: equal hashes mean equal text
    • Rebuild the hash from scratch
  3. Why does KMP never need to move backwards in the text?

    • After a mismatch, the failure table says how much of the match so far can still be the start of a new match
    • It checks every start position
    • It sorts the text first
  4. kmp("aaaa", "aa") should find [0, 1, 2], but finds [0, 2]. Which line is wrong?

    def kmp(text, pat, fail):
        k, found = 0, []
        for i, ch in enumerate(text):
            while k > 0 and ch != pat[k]:
                k = fail[k - 1]
            if ch == pat[k]:
                k += 1
            if k == len(pat):
                found.append(i - k + 1)
                k = 0

Coding tasks

  1. Write failure(pat): the KMP failure table, where fail[i] is the length of the longest proper border of pat[:i + 1].

  2. Write count_matches(text, pat): how many times pat appears in text, overlaps included, in O(n + m). (text.count doesn't count overlaps.) The pattern is never empty.