Pattern visualizer
Rabin Karp Algorithm
Comparing a pattern against every window of the text re-reads the same characters over and over. Rabin-Karp replaces each window with one number and compares numbers instead, then repairs the number as the window slides: the leaving character is subtracted out and the entering one shifted in, so a new window costs a constant amount of work rather than a fresh pass over the pattern. The catch is that a hash squeezes every possible window into a limited range of remainders, so two different strings can land on the same number. This trace uses a deliberately small modulus to make that happen twice: three windows hash equal, and only one of them really is the pattern. The character comparison after a hash hit is what separates them, which is why it belongs in the algorithm and not in a comment. Animated on: text = "abracadabra", pattern = "cad" — report every index where the pattern starts. Base 26, modulus 79, chosen so a collision actually happens..
A rolling hash, and the check you cannot skip
Looking for "cad" inside "abracadabra". Comparing the pattern against all 9 windows character by character costs up to 27 comparisons. Instead each window gets ONE number — a hash — and numbers compare in a single operation.
1FUNCTION rabinKarp(text, pat)2 m <- LENGTH(pat)3 high <- POWER(d, m - 1) MOD q4 hp <- HASH(pat)5 hw <- HASH(text[0 .. m - 1])6 FOR i <- 0 TO LENGTH(text) - m7 IF hw = hp8 IF text[i .. i + m - 1] = pat9 APPEND i TO out10 IF i < LENGTH(text) - m11 hw <- ((hw - VAL(text[i]) * high) * d + VAL(text[i + m])) MOD q12 RETURN out
← / → step · space play · Home restart