Rabin-Karp & Rolling Hashes
In short: Rabin-Karp fingerprints every window with a polynomial hash, so
comparing two windows is one number comparison instead of m character
comparisons. Sliding the window removes the leaving character's weight,
shifts, and adds the entering character, all in O(1), so the whole scan is
O(n + m) expected. A hash match is only a hint — two different windows can
collide — so every hit must be verified against the real characters before it
counts as a match.

From here on, the course builds Quarry, a small search-and-storage engine: the kind of program that sits under a log viewer, a code-search box or a document store. Each section adds one subsystem, and this one adds the text index. A user types a phrase, and Quarry says where it occurs in a pile of text without reading any character more often than it has to.
The first question is the obvious one. How do you find a pattern of length m
inside a text of length n?
The naive search, and where it wastes work
Line the pattern up at every start position and compare character by character until something differs:
On ordinary English the inner loop usually stops at the first character, so the
search is close to O(n). On repetitive text it is not. A thousand as and a
pattern of twenty as then a b make every alignment compare 21 characters
before failing, which is about n · m comparisons. Machine logs, DNA and padded
records are exactly that kind of repetitive.
text, pattern = "aaaaa", "aab"
compares = 0
for i in range(len(text) - len(pattern) + 1):
for j in range(len(pattern)):
compares += 1
if text[i + j] != pattern[j]:
break
print(compares)