Proofs: Morris-Pratt algorithm
These are the human proofs of Morris-Pratt algorithm, at full length.
Morris-Pratt outputs exactly the valid shifts full
This proof shows: correctness, termination.
Claim. For a text and a pattern with , MP-MATCHER stops and outputs exactly the shifts , , with , in increasing order. For , line L2 outputs every shift , as the definition requires.
Setup. Assume that lines L12 to L18 compute the prefix function of ; the proof is on that page. For a string , let be the length of the longest prefix of that is a suffix of and is shorter than . We use the border-chain lemma: for , the lengths of the proper borders of are exactly , in decreasing order.
Lemma 1. Let . The prefixes of of length at most that are suffixes of are exactly and the proper borders of .
Proof. If and is a suffix of , then it is a suffix of the longer suffix of , and it is a prefix of it too, so it is a border of (proper if ). Conversely, a border of is a suffix of , hence of .
Lemma 2. Let at line L6 and . After line L8, is the length of the longest prefix of that is a suffix of .
Proof. For , the prefix is a suffix of exactly when is a suffix of and . Such a is at most . So by Lemma 1, is the first value in the list with , and if there is none.
Lines L6 and L7 walk down this list, in this order, while the current value is positive and . Each step lowers by at least 1 and , so the loop stops. If it stops with , is the first good value and line L8 sets . If it stops with and , no value of the list is good, line L8 changes nothing, and .
Theorem. The claim holds.
Proof. We prove by induction on that at the start of the iteration for , and at the end for :
(I) , and the output is the increasing list of the valid shifts with .
For , line L4 sets of the empty string, and nothing is output. Assume (I) for . By Lemma 2, after line L8, , the length of the longest prefix of that is a suffix of . The shift is valid exactly when , and it is larger than all shifts output before, so lines L9 and L10 keep the second part of (I). If , then . If , the longest prefix shorter than that is a suffix of is, by Lemma 1 applied with in place of , the longest proper border of , of length , which line L11 assigns. So (I) holds for . The loop of line L5 runs times and each inner loop stops, so the algorithm stops, and (I) for is the claim.