Skip to content

Knuth-Morris-Pratt

words

Level 3 of 3

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

question 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.

placeletters abovecomparisons
1aaa3
2aab2, found
table3
all8
aab tried at 2 places of aaab, after its table.

if you chose another

  • That counts the search but leaves out the table's 3.
  • That is brute force, 3 at each place: no table, but it compares the text's second a again.
  • That is the table alone.

new numbers

question 2

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

  • abab 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.
  • b is not the pattern's first letter, a: 1 at each of 5 places, and 8 with the table.
  • aba 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.

new numbers