DryRun
AlgorithmsCourseCompare
DryRun
AlgorithmsCourseCompareGitHubLinkedIn

© 2026 DryRun. Built by Aditya Pandey.

AlgorithmsAdvancedRabin-Karp
Advancedintermediatestringhashingpattern-matching

Rabin-Karp

Rabin-Karp hashes the pattern and each text window of equal length. Matching hashes trigger direct comparison to handle collisions. Rolling hash updates each window in O(1), giving near-linear performance in practice.

Complexity

Best
O(n + m)
Average
O(n + m)
Worst
O(nm)
Space
O(1)

Implementation

vector<int> rabinKarp(string text, string pat) {
    const long long B = 256, MOD = 1000000007;
    int n = text.size(), m = pat.size();
    if (m > n) return {};
    long long hp = 0, ht = 0, h = 1;
    for (int i = 0; i < m - 1; i++) h = (h * B) % MOD;
    for (int i = 0; i < m; i++) {
        hp = (hp * B + pat[i]) % MOD;
        ht = (ht * B + text[i]) % MOD;
    }
    vector<int> res;
    for (int i = 0; i <= n - m; i++) {
        if (hp == ht && text.substr(i, m) == pat) res.push_back(i);
        if (i < n - m) {
            ht = (B * (ht - text[i] * h % MOD + MOD) + text[i + m]) % MOD;
        }
    }
    return res;
}

How It Works

1.Rolling Hash

Avoids recomputing each window hash from scratch by updating in O(1).

2.Collision Handling

Equal hashes are verified by direct substring comparison.

3.Use Cases

Good for multiple-pattern checks and plagiarism-like scanning workflows.

Related Algorithms

CpuKMP (Knuth-Morris-Pratt)CpuBoyer-Moore

Test Your Knowledge

Quiz coming soon for this algorithm.

Back to all algorithms