Also called KMP algorithm and Knuth-Morris-Pratt algorithm.
fresh numbers
The test's questions that a run answers, asked again on new numbers whenever you like. The answer, its working and the reason for every other choice come from knuth-morris-pratt's own run on the numbers shown.
choose one
1question 1
Knuth-Morris-Pratt looks for aab in aaab. How many comparisons does it make, its table included?
the answer, and why
the answer is C
The table for aab: a matches a, 1; b differs from a, falls back to nothing and differs from a again, 2. The search: a and a match, b is not a, 3. The 2 a's matched end with a border a, so the pattern moves on 1 place: its second a matches the same text a, and b matches b, 2. 3 + 3 + 2 is 8.
place
letters above
comparisons
1
aaa
3
2
aab
2, found
table
3
all
8
aab tried at 2 places of aaab, after its table.
if you chose another
AThat counts the search but leaves out the table's 3.
BThat is brute force, 3 at each place: no table, but it compares the text's second a again.
Each search looks for abab in a text of 8 letters. Which makes Knuth-Morris-Pratt compare the most, its table included?
the answer, and why
the answer is B
The table for abab costs 3. In aaaaaaaa each a matches the pattern's a, then the next a is not b. Only a had matched, and one letter has no border, so that same text a is compared with the pattern's a. That is 2 at each of 5 places, 10, and 13 with the table.
if you chose another
Aabab is found at places 1, 3 and 5. Its border ab lines up each time, so only 2 new letters: 4 + 2 + 2, and 11 with the table.
Cb is not the pattern's first letter, a: 1 at each of 5 places, and 8 with the table.
Daba matches, 3; the next a is compared 3 times as the pattern falls back twice, 3. Then b, a and b match, 3 more, and abab is found at place 4: 9, and 12 with the table.