Rabin Karp Algorithm

Pattern: Pattern matching

hard

Give every window of the text a number (a rolling hash) that can be updated in O(1) when the window slides. Only where the window's hash equals the pattern's hash do you compare the letters.

The problem

Given a text and a pattern, return every index where the pattern starts in the text, in increasing order, using the Rabin-Karp method. Indexes count from 0 and matches may overlap. For example, "AABAACAADAABAABA" with "AABA" gives [0, 9, 12].

The link above is a GeeksforGeeks article. The function name rabinKarp is this guide's own. An empty list means no match.

Think first

  • Comparing a window with the pattern costs O(m). How could one number tell you that most windows cannot match?
  • When the window slides by one, which character leaves and which arrives?
  • If two hashes are equal, are the strings equal?

Hints

    Brute force, and why it fails

    Compare the pattern at every start: O(n × m). Rolling hashes make each step O(1), so the expected time is O(n + m), plus O(m) for each real match.

    The key insight

    A rolling hash summarises a window in one number that can be updated instead of recomputed. Comparing numbers first filters out almost every non-match cheaply.

    Dry run

    a0 
    a1 
    a2 
    a3 
    a4 
    m2

    text = aaaaa and pattern = aa. With base B, the hash of a window of two letters x y is x × B + y.

    Step 1 of 4

    The plan

    high = B^(m-1) mod P
    hp = hash(pattern), ht = hash(text[0 .. m - 1])
    for i from 0 to n - m:
        if hp == ht and text[i .. i + m - 1] == pattern: record i
        if i + m < n:
            ht = ((ht - text[i] * high) * B + text[i + m]) mod P
    

    Complexity

    Time
    O(n + m) expected
    Space
    O(1)

    Each slide is O(1). Letter checks happen only on hash matches. Many clashes could make it O(n × m), but with a large prime that is very unlikely. Apart from the output, only a few numbers are stored.

    Edge cases

    • Pattern longer than text: no matches.
    • Overlapping matches, as in "aaaaa" with "aa".
    • Negative values after subtracting: add P before taking the remainder in Java and C++.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public List<Integer> rabinKarp(String text, String pattern) {
            final long MOD = 1_000_000_007L, BASE = 256;
            int n = text.length(), m = pattern.length();
            List<Integer> out = new ArrayList<>();
            if (m > n) return out;
            long high = 1;                           // BASE^(m-1), the weight of the character that leaves
            for (int k = 1; k < m; k++) high = high * BASE % MOD;
            long hp = 0, ht = 0;
            for (int k = 0; k < m; k++) {
                hp = (hp * BASE + pattern.charAt(k)) % MOD;
                ht = (ht * BASE + text.charAt(k)) % MOD;
            }
            for (int i = 0; ; i++) {
                if (hp == ht && text.regionMatches(i, pattern, 0, m)) out.add(i);   // equal hashes: check the letters
                if (i + m == n) break;
                ht = (ht - text.charAt(i) * high % MOD + MOD) % MOD;                // drop the left character
                ht = (ht * BASE + text.charAt(i + m)) % MOD;                         // add the next one
            }
            return out;
        }
    }

    C++

    class Solution {
    public:
        vector<int> rabinKarp(string text, string pattern) {
            const long long MOD = 1000000007LL, BASE = 256;
            int n = static_cast<int>(text.size()), m = static_cast<int>(pattern.size());
            vector<int> out;
            if (m > n) return out;
            long long high = 1;                      // BASE^(m-1), the weight of the character that leaves
            for (int k = 1; k < m; k++) high = high * BASE % MOD;
            long long hp = 0, ht = 0;
            for (int k = 0; k < m; k++) {
                hp = (hp * BASE + static_cast<unsigned char>(pattern[k])) % MOD;
                ht = (ht * BASE + static_cast<unsigned char>(text[k])) % MOD;
            }
            for (int i = 0; ; i++) {
                if (hp == ht && text.compare(i, m, pattern) == 0) out.push_back(i);   // equal hashes: check letters
                if (i + m == n) break;
                ht = (ht - static_cast<unsigned char>(text[i]) * high % MOD + MOD) % MOD;   // drop the left character
                ht = (ht * BASE + static_cast<unsigned char>(text[i + m])) % MOD;          // add the next one
            }
            return out;
        }
    };

    Python

    class Solution:
        def rabinKarp(self, text: str, pattern: str) -> list[int]:
            MOD, BASE = 1_000_000_007, 256
            n, m = len(text), len(pattern)
            out = []
            if m > n:
                return out
            high = pow(BASE, m - 1, MOD)             # the weight of the character that leaves
            hp = ht = 0
            for k in range(m):
                hp = (hp * BASE + ord(pattern[k])) % MOD
                ht = (ht * BASE + ord(text[k])) % MOD
            for i in range(n - m + 1):
                if hp == ht and text[i:i + m] == pattern:
                    out.append(i)                    # equal hashes: check the letters
                if i + m < n:
                    ht = ((ht - ord(text[i]) * high) * BASE + ord(text[i + m])) % MOD   # drop left, add next
            return out

    Common mistakes

    • Trusting the hash without comparing letters.
    • Forgetting to add P after the subtraction, which gives negative hashes in Java and C++.
    • Overflowing the multiplication: keep values below P so value × B fits in 64 bits.

    Similar problems