Python 3.11+
The code uses standard Python syntax and containers supported by the browser Judge. The Rabin-Karp proof does not depend on a minor Python release.
Verify in Python docs(opens in a new tab)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 computes a pattern hash and same-width text-window hashes. Unequal hashes reject a window quickly; equal hashes identify candidates, not proof.
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.
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 traceImplement 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.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
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 tracePredict 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. |
| 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.
Different strings can collide under any fixed-size hash. Compare the actual substring or symbols whenever fingerprints match to preserve correctness.
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 matchesImplement 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.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
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 matchesUse 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.
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 3.11+
The code uses standard Python syntax and containers supported by the browser Judge. The Rabin-Karp proof does not depend on a minor Python release.
Verify in Python docs(opens in a new tab)Interview bounds depend on the stated representation, input model, and real Python operations.
| Operation | Average | Worst | Interview note |
|---|---|---|---|
| Window hash trace | O(n + log(width)) | O(n + log(width)) | For bounded-cost modular arithmetic: first window, modular power, then one update per start. |
| Verified exact matching | O(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. |
O(n) window trace or match output; rolling state itself O(1) for fixed-size parameters.
These are the mistakes most likely to survive a happy-path example and fail a boundary case.
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.
matched=hash_a==hash_bmatched=hash_a==hash_b and text==patternWhere you will hit this: Roll a Window Hash(opens in a new tab)
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.
value=(value*base+ord(incoming))%modulusvalue=(value-ord(outgoing)*highest)%modulus
value=(value*base+ord(incoming))%modulusWhere you will hit this: Roll a Window Hash(opens in a new tab)
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).
highest=pow(base,width,modulus)highest=pow(base,width-1,modulus)Where you will hit this: Lowest Common Ancestor in a BST(opens in a new tab)
Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.
python-docs · checked 2026-07-27