1. Gyanastra
  2. Algorithms
  3. String Matching: Naive Search and Rabin-Karp
  4. Rabin-Karp
Free lesson, no account needed 4 min read

Algorithms · String Matching: Naive Search and Rabin-Karp

Rabin-Karp

3.1 The idea

Instead of comparing mm characters at every shift, compare a hash of the window with the hash of the pattern. Only when the hashes agree do we verify character by character. The magic is that the window hash can be updated in O(1)O(1) when the window slides by one.

3.2 The polynomial hash

Interpret a length-mm string X=x0x1…xm−1X = x_0 x_1 \dots x_{m-1} (each xix_i mapped to a digit in {0,…,d−1}\{0,\dots,d-1\}) as a base-dd number:

H(X)=∑i=0m−1xi d m−1−i=x0dm−1+x1dm−2+⋯+xm−1.H(X) = \sum_{i=0}^{m-1} x_i \, d^{\,m-1-i} = x_0 d^{m-1} + x_1 d^{m-2} + \dots + x_{m-1}.

For the window starting at ss:

h(s)=∑i=0m−1T[s+i] d m−1−i.h(s) = \sum_{i=0}^{m-1} T[s+i]\, d^{\,m-1-i}.

We reduce everything modulo a prime qq so the numbers fit in a machine word. All arithmetic below is mod qq.

3.3 The rolling-hash recurrence (the heart of the algorithm)

When the window slides from ss to s+1s+1, we drop T[s]T[s] (which carried weight dm−1d^{m-1}) and append T[s+m]T[s+m] (weight d0=1d^0 = 1):

 h(s+1)=(d (h(s)−T[s] d m−1)+T[s+m]) mod q \boxed{\,h(s+1) = \Big(d\,\big(h(s) - T[s]\,d^{\,m-1}\big) + T[s+m]\Big) \bmod q\,}

Why each term: multiply by dd shifts every remaining digit one place left (weight dm−1−i→dm−id^{m-1-i} \to d^{m-i}); subtracting T[s]dm−1T[s]d^{m-1} removes the outgoing digit before the multiply (equivalently, after multiplying by dd one would subtract T[s] dmT[s]\,d^{m}); adding T[s+m]T[s+m] inserts the new digit at weight d0d^0.

Precomputation: h(0)h(0) costs O(m)O(m) (Horner's rule), and dm−1 mod qd^{m-1} \bmod q is computed once by fast exponentiation in O(log⁡m)O(\log m). Then each of the n−mn-m slides costs O(1)O(1).

3.4 The algorithm

RABIN-KARP(T, P, d, q)
  n = length(T); m = length(P)
  hP = 0; hT = 0; h = d^(m-1) mod q        // h = d^{m-1} mod q
  for i = 0 to m-1
      hP = (d*hP + P[i]) mod q
      hT = (d*hT + T[i]) mod q
  for s = 0 to n-m
      if hP == hT
          if T[s..s+m-1] == P            // verify to rule out spurious hit
              print "Pattern occurs at shift" s
      if s < n-m
          hT = (d*(hT - T[s]*h) + T[s+m]) mod q

3.5 Spurious hits

If h(s)=H(P) mod qh(s) = H(P) \bmod q but the window is not equal to PP, we call it a spurious hit (false positive). It happens because different strings can share a residue mod qq. Spurious hits are caught by the explicit verification step, so they never cause a wrong answer — only extra work.

  • Expected running time: O(n+m)O(n+m). If qq is a large prime (say ≥109\ge 10^9, chosen so that d⋅qd\cdot q fits in a machine word), the probability that a random non-matching window collides is about 1/q1/q, so the expected number of spurious hits over n−m+1n-m+1 windows is ≈(n−m+1)/q\approx (n-m+1)/q, negligible. Total expected cost =O(n+m)= O(n+m).
  • Worst case: O(nm)O(nm). If many windows trigger verification, each verification costs up to mm comparisons, giving (n−m+1)m=O(nm)(n-m+1)m = O(nm). This happens for genuinely matching text such as T=anT = a^n, P=amP = a^m (every shift is a true match), or for an adversarial input with many spurious hits. In general the expected time is O(n+m(v+n/q))O(n + m(v + n/q)) where vv is the number of valid shifts.
  • Space: O(1)O(1) extra (just a few integers).

3.6 Comparison table

FeatureNaiveRabin-Karp
PreprocessingO(1)O(1)O(m)O(m) (hash of PP) + O(log⁡m)O(\log m) for dm−1d^{m-1}
Matching (expected, random text)O(n)O(n)O(n+m)O(n+m)
Matching (worst)O(nm)O(nm)O(nm)O(nm)
Extra spaceO(1)O(1)O(1)O(1)
Key ideacompare characterscompare hashes, verify on hit
Sensitive torepetitive textchoice of qq (spurious hits)

Pages 1–2 of 2