Algorithms · Visualized

String: Rabin-Karp

String Matching

Find a pattern inside a text efficiently — from the naive slide to prefix-function smartness.

Rabin-Karp searches for a pattern by comparing hash values instead of raw characters. Time: O(n + m) average, O(n × m) — rare, occurs with many hash collisions worst; space: O(1).

Big-O: Naive O(n·m); KMP & Z O(n+m); Rabin–Karp O(n+m) average with hashing.

Rabin-Karp

String Matching

Rabin-Karp searches for a pattern by comparing hash values instead of raw characters. It computes a hash of the pattern and a 'rolling hash' of each window of text (updating it in O(1) as the window slides), only doing a full character-by-character check when the hashes match, to rule out hash collisions.

How Rabin-Karp Works

  1. Compute a hash value for the pattern.
  2. Compute a hash value for the first window of text (same length as the pattern).
  3. Compare the text window's hash with the pattern's hash; if they match, do a full character comparison to confirm (avoiding false positives from hash collisions).
  4. Slide the window forward by one character, updating the hash efficiently using a 'rolling hash' formula (remove the leftmost character's contribution, add the new rightmost character's contribution) — without rehashing the whole window from scratch.
  5. Repeat comparing hashes and confirming matches until the window reaches the end of the text.

Rabin-Karp Worked Example

Input: {text: GEEKS FOR GEEKS, pattern: GEEK}

Hash of 'GEEK' is computed once. Hash of text window 'GEEK' (0-3) matches → confirm character by character → match at index 0. Slide window, roll the hash forward efficiently for each new window, checking for matches. A second full match of 'GEEK' is found starting at index 10.

String: Rabin-KarpO(n + m) avg
Hash the pattern and roll a hash window over the text, verifying on matches.
t
G
E
E
K
S
F
O
R
G
E
E
K
S
01234567891011121314
p
G
E
E
K
0123
pattern hash27
window hash27
prime101
Step 1 / 7
Default Current / Compare Swap / Write Settled Active / Path Pivot / Reject Locked (hollow) Target
Rabin–Karp: hash the pattern and slide a hash window over the text (mod 101).
Python · String Matching in Code
def rabin_karp(text, pat):
    m, n = len(pat), len(text)
    if m > n:
        return []
    mod = 10**9 + 7
    base = 256
    hp = 0
    hw = 0
    power = 1
    for i in range(m):
        hp = (hp * base + ord(pat[i])) % mod
        hw = (hw * base + ord(text[i])) % mod
        power = power * base % mod
    out = []
    for i in range(n - m + 1):
        if hp == hw and text[i:i + m] == pat:
            out.append(i)
        if i < n - m:
            hw = (hw * base - ord(text[i]) * power + ord(text[i + m])) % mod
    return out

Behind the Scenes Execution

Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.

Rabin-Karp Time & Space Complexity

BestO(n + m)
AverageO(n + m)
WorstO(n × m) — rare, occurs with many hash collisions
SpaceO(1)

When to Use Rabin-Karp

  • Plagiarism detection systems, comparing many document fingerprints (hashes) quickly.
  • Searching for multiple patterns simultaneously, since hashes for different patterns can be checked together efficiently.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Keep the momentum going

Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.