Skip to contentKEEP THE CRAFTTHE SANCTUARY

Rabin-Karp

Maintain a polynomial fingerprint for each fixed-width window, then verify every equal-hash candidate with exact symbols. Account separately for rolling updates, true matches and collision-driven verification.

1 practice exercise1 interview problem

Recognize it when Many equal-width windows need quick rejection against a pattern fingerprint.

Checking your account…

Rabin-Karp Code Labs

Compare Rolling Window Fingerprints

Rabin-Karp computes a pattern hash and same-width text-window hashes. Unequal hashes reject a window quickly; equal hashes identify candidates, not proof.

Remove Leaving Add Entering

A rolling polynomial hash subtracts the leaving character’s highest-place contribution, multiplies by the base, and adds the entering character, reducing modulo m after each step.

Trace Rolling Hash Windows

Reference
def rolling_hash_trace(text,width,base,modulus):
    if width>len(text):return []
    highest=pow(base,width-1,modulus);value=0
    for character in text[:width]:value=(value*base+ord(character))%modulus
    trace=[[0,value]]
    for start in range(1,len(text)-width+1):
        value=(value-ord(text[start-1])*highest)%modulus;value=(value*base+ord(text[start+width-1]))%modulus;trace.append([start,value])
    return trace
Practice

Implement rolling_hash_trace(text,width,base,modulus). Map characters with ord and return [start,hash] for each fixed-width window. width, base and modulus are positive integers.

Public tests

  • Remove leaving and append entering symbol

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Trace Rolling Hash Windows

def rolling_hash_trace(text,width,base,modulus):
    if width>len(text):return []
    highest=pow(base,width-1,modulus);value=0
    for character in text[:width]:value=(value*base+ord(character))%modulus
    trace=[[0,value]]
    for start in range(1,len(text)-width+1):
        value=(value-ord(text[start-1])*highest)%modulus;value=(value*base+ord(text[start+width-1]))%modulus;trace.append([start,value])
    return trace

Remove b Before Shifting bc into cd

Predict the arithmetic in the existing rolling trace. The small modulus makes the computation easy to inspect; it does not make these numeric fingerprints unique strings.

Step Executed statement State Why
Outgoing coefficient highest=pow(base,width-1,modulus);value=0 highest=10, value=0 A width-2 hash is first_code*10 + second_code.
Build first window for character in text[:width]:value=(value*base+ord(character))%modulus after b then c: value=69 (98*10+99) modulo 101 equals 69.
Record first window trace=[[0,value]] trace=[[0,69]] The initial row is constructed once after the entire width-2 build loop.
Remove outgoing b value=(value-ord(text[start-1])*highest)%modulus start=1, value=99 69-980 modulo 101 leaves the c contribution.
Shift and append d value=(value*base+ord(text[start+width-1]))%modulus;trace.append([start,value]) value=80, trace=[[0,69],[1,80]] (99*10+100) modulo 101 fingerprints exactly cd.
Oversized call if width>len(text):return [] [] There are no complete width-2 windows in a one-symbol text.
Print Output
print(rolling_hash_trace("bcd",2,10,101)) [[0, 69], [1, 80]]
print(rolling_hash_trace("b",2,10,101)) []

The exact matcher verifies with a substring slice. Repeated real matches trigger those copies too, so expected linear rolling work must not be described as a universal linear bound for full all-match verification.

Verify Every Hash Match

Different strings can collide under any fixed-size hash. Compare the actual substring or symbols whenever fingerprints match to preserve correctness.

Find Rabin-Karp Matches

Reference
def rabin_karp(text,pattern):
    if pattern=="":return list(range(len(text)+1))
    width=len(pattern)
    if width>len(text):return []
    base=257;modulus=1000000007;highest=pow(base,width-1,modulus)
    pattern_hash=window_hash=0
    for p,t in zip(pattern,text):pattern_hash=(pattern_hash*base+ord(p))%modulus;window_hash=(window_hash*base+ord(t))%modulus
    matches=[]
    for start in range(len(text)-width+1):
        if window_hash==pattern_hash and text[start:start+width]==pattern:matches.append(start)
        if start+width<len(text):window_hash=(window_hash-ord(text[start])*highest)%modulus;window_hash=(window_hash*base+ord(text[start+width]))%modulus
    return matches
Practice

Implement rabin_karp(text,pattern). Return all match starts including overlaps and verify hash candidates. Empty pattern matches every boundary 0..len(text); a longer pattern has no matches.

Public tests

  • Verify every fingerprint collision candidate

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Find Rabin-Karp Matches

def rabin_karp(text,pattern):
    if pattern=="":return list(range(len(text)+1))
    width=len(pattern)
    if width>len(text):return []
    base=257;modulus=1000000007;highest=pow(base,width-1,modulus)
    pattern_hash=window_hash=0
    for p,t in zip(pattern,text):pattern_hash=(pattern_hash*base+ord(p))%modulus;window_hash=(window_hash*base+ord(t))%modulus
    matches=[]
    for start in range(len(text)-width+1):
        if window_hash==pattern_hash and text[start:start+width]==pattern:matches.append(start)
        if start+width<len(text):window_hash=(window_hash-ord(text[start])*highest)%modulus;window_hash=(window_hash*base+ord(text[start+width]))%modulus
    return matches

Choose Modulus Base and Collision Policy

Use a modulus and base appropriate to the symbol domain; double hashing can reduce candidate frequency but does not replace verification when correctness is exact. Empty and oversized patterns need explicit contracts.

Explain It in an Interview

Say: “The rolling hash updates each alignment in O(1), but a hash match is only a candidate, so I verify the text.” State O(n + m + C*m + log(m+1)) work for C verified hash candidates with bounded modular arithmetic; both collisions and repeated true matches can make verification quadratic. Include the O(n+1) empty-pattern output, overlap handling, and normalization.

Python Version Note

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Window hash traceO(n + log(width))O(n + log(width))For bounded-cost modular arithmetic: first window, modular power, then one update per start.
Verified exact matchingO(n+m+C*m+log(m+1))O(n * max(1,m) + m + log(m+1))C counts hash-equal windows, including true matches; each substring slice and verification can cost O(m). Empty patterns return all n+1 boundaries in O(n+1) time.

Space

O(n) window trace or match output; rolling state itself O(1) for fixed-size parameters.

Assumptions

  • Python integers grow with modulus/base bit length, so arithmetic is not constant for unbounded parameters.
  • The match Lab chooses fixed constants; small demonstration moduli are deliberately collision-prone.

Invariants Worth Saying Aloud

  1. The current fingerprint equals the polynomial hash of exactly the current window modulo modulus.
  2. The outgoing symbol is removed with its highest-position coefficient before shifting.
  3. An accepted occurrence passed both fingerprint and actual substring equality.

When To Use Or Avoid Rabin-Karp

Use It When

  • Use verified fingerprints to filter candidate alignments.
  • Use KMP when deterministic linear worst-case exact matching is required.

Choose Another Tool When

  • Do not return equality solely from one or several fingerprints when exact correctness is required.
  • Many true repeated matches can make verification expensive even with no accidental collision.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Trusting a colliding fingerprint

a and f both have ord modulo 5 equal to 2. Hash equality alone accepts a different character.

Prevent it: Combine hash equality with exact content equality.

Avoid

matched=hash_a==hash_b

Use instead

matched=hash_a==hash_b and text==pattern

Shifting without removing the outgoing term

The bc hash is 69 for base 10 modulo 101. Shifting it directly and appending d keeps b in the new cd window.

Prevent it: Subtract ord(outgoing)*highest before shifting.

Avoid

value=(value*base+ord(incoming))%modulus

Use instead

value=(value-ord(outgoing)*highest)%modulus
value=(value*base+ord(incoming))%modulus

Using base to the width instead of width minus one

The first symbol of a width-2 polynomial has coefficient base^1, not base^2. Wrong removal leaves a different residual.

Prevent it: Compute pow(base,width-1,modulus).

Avoid

highest=pow(base,width,modulus)

Use instead

highest=pow(base,width-1,modulus)

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.