1 let k ← k + 1 Efficiency of the search algorithm Assuming the prior existence of the table T, the search portion of the Knuth–Morris–Pratt algorithm has complexity O(n), where n is the length of S and the O is big-O notation. Except for the fixed overhead incurred in entering and exiting the function, all the computations are performed in the while loop. To bound the number of iterations of this loop; observe that T is constructed so that if a match which had begun at S[m] fails while comparing S[m + i] to W[i], then the next possible match must begin at S[m + (i - T[i])]. In particular, the next possible match must occur at a higher index than m, so that T[i] < i. This fact implies that the loop can execute at most 2n times, since at each iteration it executes one of the two branches in the loop. The first branch invariably increases i and does not change m, so that the index m + i of the currently scrutinized character of S is increased. The second branch adds i - T[i] to m, and as we have seen, this is always a positive number. Thus the location m of the beginning of the current potential match is increased. At the same time, the second branch leaves m + i unchanged, for m gets i - T[i] added to it, and immediately after T[i] gets assigned as the new value of i, hence new_m + new_i = old_m + old_i - T[old_i] + T[old_i] = old_m + old_i. Now, the loop ends if m + i = n; therefore, each branch of the loop can be reached at most n times, since they respectively increase either m + i or m, and m ≤ m + i: if m = n, then certainly m + i ≥ n, so that since it increases by unit increments at most, we must have had m + i = n at some point in the past, and therefore either way we would be done. Thus the loop executes at most 2n times, showing that the time complexity of the search algorithm is O(n). Here is another way to think about the runtime: Let us say we begin to match W and S at position i and p. If W exists as a substring of S at p,