Slide and compare
transcript
Find a word in a long text. Hold the word on a paper strip. Slide it along, one place at a time. Compare letter by letter. Stop at the first mismatch.
Put the pattern at the start. At shift zero, a and b match. Then c is not d. Slide one place and try again. Most shifts fail on the first letter. Shift six matches all three letters. That took thirteen comparisons in all.
Now try a text that repeats. Each shift matches three letters, then fails. There are seven shifts of four comparisons.
Thirteen comparisons found it. A repeating text is the worst case. Aaab in aaaaaaaaab takes twenty eight. A long repeating text can reach a billion.
Two faster methods exist. This lesson only names them. A rolling hash compares numbers first, and checks letters later. KMP never steps back in the text after a mismatch. In real code, call the library search first.
Slide the pattern. Stop at each mismatch. Full breakdown in the lecture.