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 nno in nnnnnno. How many comparisons does it make, its table included?

the answer, and why

the answer is A

The table for nno: n matches n, 1; o differs from n, falls back to nothing and differs from n again, 2. The search: n and n match, o is not n, 3. Then, 4 times, the 2 n's matched end with a border n, so the pattern moves on 1 place: its second n matches the same text n, and the next letter is compared, 2 each time. 3 + 3 + 8 is 14.

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 n's again.
  • That is the table alone.

new numbersthe test page's numbers

question 2

Each search looks for rrbb in a text of eight letters. Which makes Knuth-Morris-Pratt compare the most, its table included?

the answer, and why

the answer is A

The method never goes back in the text, but a letter that differs is compared again after each fall back. rrrrrrrb, rrbb takes 15 comparisons, its table included, the most of the four.

if you chose another

  • That takes 10 comparisons, its table included, fewer than 15.
  • That takes 13 comparisons, its table included, fewer than 15.
  • That takes 11 comparisons, its table included, fewer than 15.

new numbersthe test page's numbers