Algorithm Search⌘K

Proofs: Shift-Or algorithm

These are the human proofs of Shift-Or algorithm, at full length.

Shift-Or outputs exactly the valid shifts full

This proof shows: correctness, termination.

Claim. For a text T[0…n−1]T[0 \ldots n-1] and a pattern P[0…m−1]P[0 \ldots m-1], SHIFT-OR(T,P)(T, P) stops after nn iterations and outputs exactly the shifts ss, 0≤s≤n−m0 \le s \le n - m, with T[s…s+m−1]=PT[s \ldots s+m-1] = P, in increasing order.

For m=0m = 0, line L2 outputs every shift, which is correct. Let m≥1m \ge 1, and write DjD_j for digit jj of DD, 0≤j<m0 \le j < m.

Masks. After lines L3 and L4, digit jj of B[c]B[c] is 0 exactly when P[j]=cP[j] = c: line L3 sets all digits to 1, and line L4 clears digit jj of B[P[j]]B[P[j]] for each jj and nothing else.

Invariant. After line L7 in the iteration for ii:

(I) for every 0≤j<m0 \le j < m, Dj=0D_j = 0 exactly when j≤ij \le i and P[0…j]=T[i−j…i]P[0 \ldots j] = T[i - j \ldots i].

Set D(−1)=1mD^{(-1)} = 1^m, the value of line L5; it satisfies (I) for i=−1i = -1, since no j≤−1j \le -1 exists.

Step. Let DD be the value before line L7 in iteration ii, satisfying (I) for i−1i - 1, and D′D' the value after it. For j≥1j \ge 1, digit jj of D≪1D \ll 1 is Dj−1D_{j-1}; digit 0 of D≪1D \ll 1 is 0. The AND with 1m1^m only removes digits ≥m\ge m. So

D0′=B[T[i]]0,Dj′=Dj−1ORB[T[i]]j(1≤j<m).D'_0 = B[T[i]]_0, \qquad D'_j = D_{j-1} \mathbin{\mathrm{OR}} B[T[i]]_j \quad (1 \le j < m).

For j=0j = 0: D0′=0D'_0 = 0 exactly when P[0]=T[i]P[0] = T[i], which is (I) for j=0j = 0. For j≥1j \ge 1: Dj′=0D'_j = 0 exactly when Dj−1=0D_{j-1} = 0 and P[j]=T[i]P[j] = T[i], that is, by (I) for i−1i - 1, when j−1≤i−1j - 1 \le i - 1, P[0…j−1]=T[i−j…i−1]P[0 \ldots j-1] = T[i - j \ldots i-1] and P[j]=T[i]P[j] = T[i], which is exactly j≤ij \le i and P[0…j]=T[i−j…i]P[0 \ldots j] = T[i-j \ldots i]. So (I) holds for ii.

Output. By (I) with j=m−1j = m - 1, line L8 outputs i−m+1i - m + 1 exactly when m−1≤im - 1 \le i and T[i−m+1…i]=PT[i - m + 1 \ldots i] = P, that is, exactly when s=i−m+1s = i - m + 1 is a valid shift with 0≤s≤n−m0 \le s \le n - m. Each valid shift ss is output in the iteration i=s+m−1i = s + m - 1, and these iterations come in increasing order of ss. The loop has nn iterations, each of constant work on a fixed number of words, so the algorithm stops. ■\blacksquare

Back to Shift-Or algorithm