PrepStack · Markdown HTML

Rolling hash / Rabin-Karp

String matching, hashing, and palindrome · HTML

Formal shape

H[i+1]=(H[i]base+code(s[i])) mod M; hash(l,r)=H[r]-H[l]base^(r-l) mod M.

Recognition signals

False friends

SignalWhy it is different
No probabilistic error is tolerableA single hash can collide; verify candidates, double-hash, or use a deterministic algorithm.
Approximate textual similarityHashing tests exact equality, not edit distance.

Core invariant

A prefix hash is a left-to-right polynomial; after power alignment, equal substrings have equal fingerprints.

State, transition, and processing order

ItemDefinition
StatePrefix hashes, powers of base, and modulus; high-reliability uses two independent parameter sets.
TransitionAppend one character to extend the prefix; extract a range by subtracting and power-aligning two prefixes.
Frontier / orderPreprocessing advances one character at a time; later window checks move endpoints without rescanning interiors.

Python skeleton

class RollingHash:
    def __init__(self, s, base=911382323, mod=1_000_000_007):
        self.base, self.mod = base, mod
        self.h = [0] * (len(s)+1)
        self.p = [1] * (len(s)+1)
        for i, ch in enumerate(s):
            self.h[i+1] = (self.h[i]*base + ord(ch)+1) % mod
            self.p[i+1] = self.p[i]*base % mod
    def get(self, left, right):
        return (self.h[right] - self.h[left]*self.p[right-left]) % self.mod

def probably_equal_substrings(s, a, b, length):
    rh = RollingHash(s)
    return rh.get(a,a+length) == rh.get(b,b+length)

Correctness sketch

  1. The prefix recurrence is exactly a polynomial in character codes.
  2. Subtracting the scaled left prefix leaves only coefficients in [l,r).
  3. Equal strings have equal coefficient sequences and therefore equal hashes.
  4. The converse is probabilistic; a second hash or direct verification controls collisions.

Complexity

TimeSpaceParameters
O(n) preprocessing and O(1) per substring hashO(n)string length n; collision risk depends on base, modulus, and number of hashes

Edge cases

Error patterns

PatternWhy it fails / fix
No power alignmentRaw prefix subtraction leaves position-dependent weights.
Treating equality as proofA collision remains unless candidates are verified.
Mismatched parametersHashes using different base or modulus are incomparable.

Selection and exclusion rules

RelationTemplateBoundary
alternativeTrie prefix searchThe task compares many fixed-length substrings rather than navigating prefixes.

Original micro-example

PartDetail
ResultBoth hashes match and both substrings are cab.
ScenarioCompare [0,3) and [3,6) in cabcab.
WalkthroughSubtracting and aligning the second range yields the same coefficient sequence as the first.

Recall prompts

My notes