Proofs: Rabin-Karp algorithm
These are the human proofs of Rabin-Karp algorithm, at full length.
Rabin-Karp outputs exactly the occurrences of the pattern full
This proof shows: correctness, termination.
Claim. For every text , every pattern and every value of the base drawn at line L3, RABIN-KARP stops and outputs, in increasing order, exactly the shifts with and (all from to when ).
Notation. All hash values are in . For a string of length , , and for .
Lemma 1 (Horner's rule). After line L6, and .
Proof. Let be the value of after passes, with . By induction on , : the case is the empty sum, and modulo . For this is . The same argument with gives .
Lemma 2 (the window update). For , , where .
Proof. Work in the ring of integers modulo . By definition , and the term with is . So
Put . The sum becomes , and the last term is the term of . The reduction modulo returns the representative in , which is .
Lemma 3 (loop invariant). If , then at line L8 in the pass with shift , and .
Proof. By induction on . For , this is Lemma 1. Line L4 sets , and no line changes or after line L6. If the claim holds for , then line L10 is true and line L11 sets to the value of Lemma 2, which is .
Lemma 4 (the test at one shift). If and , the pass for outputs if and only if .
Proof. If , then the two strings are the same, so , and by Lemma 3 the test of line L8 is true. Line L9 compares the window with character by character, finds them equal, and outputs . If , then either the test of line L8 is false, or it is true and line L9 finds a position where the window and differ. In both cases nothing is output for . The pass for outputs no other shift.
Termination. Each loop runs over a finite range of integers: line L6 runs times, line L7 runs times, and the comparison of line L9 looks at most at positions. So the algorithm stops.
Theorem. The claim holds.
Proof. If , line L1 outputs , and the empty pattern occurs at exactly these shifts. If , no shift satisfies , and line L2 stops with no output. Otherwise, line L7 visits each from to once, in increasing order, and by Lemma 4 it outputs exactly when occurs at . The proof does not use any property of or of , so the output is correct for every base.
Remark (where randomness enters). The choice of affects only how often line L9 runs on a window that is not an occurrence. For a fixed and and a shift that is not an occurrence, the window and are distinct strings of the same length , and by the polynomial hash collision bound when is prime and is uniform on . This gives the expected time on the main page.