V

Algorithm Visualizer

ZHEN
Share on WeiboShare on XGitHub repositoryAuthor website
Learning ToolsAlgorithm Complexity ReferenceAlgorithm Learning Paths
Data StructuresArrayLinked ListStackQueue and DequeBinary Search TreeBinary HeapHash TableGraphTrieDisjoint Set UnionLRU CacheSkip ListSegment TreeB+ TreeBloom FilterFenwick Tree
SortingBubble SortCocktail Shaker SortBitonic SortSelection SortInsertion SortBinary Insertion SortShell SortMerge SortTop-Down Merge SortQuick SortThree-Way Quick SortDual-Pivot Quick SortHeap SortCounting SortRadix SortBucket Sort
Graph AlgorithmsDijkstra's Shortest PathKruskal's Minimum Spanning TreePrim's Minimum Spanning TreeBellman-Ford Shortest PathsTopological SortFloyd-WarshallStrongly Connected Components2-SATMaximum FlowBipartite MatchingLowest Common AncestorEulerian Path
Dynamic ProgrammingEdit Distance0/1 KnapsackUnbounded KnapsackLongest Common SubsequenceLongest Increasing SubsequenceCoin ChangeStone MergingTraveling Salesperson DPTree Dynamic ProgrammingDigit DPRerooting DP
Backtracking and SearchN-QueensSubsetsPermutationsCombination SumMaze Solving with DFSNumber of IslandsWord SearchSudoku SolverA* Search
StringsKMP String MatchingRabin-Karp String MatchingBoyer-Moore String MatchingManacher's Longest Palindromic SubstringSuffix ArrayLCP ArrayAho-Corasick AutomatonZ Function
Math and Number TheorySieve of EratosthenesLinear SieveEuclidean AlgorithmBinary ExponentiationExtended Euclidean AlgorithmChinese Remainder TheoremEuler's Totient FunctionMiller-Rabin Primality TestFast Fourier TransformPollard's Rho Factorization
Computational GeometryConvex HullRotating CalipersClosest Pair of PointsLine Segment IntersectionBentley-Ottmann Sweep Line
SearchingBinary SearchLower and Upper BoundSearch in a Rotated Sorted ArrayBinary Search on the AnswerTernary Search

Rabin-Karp String Matching

Rolling hashes for constant-time window screening

Compare fingerprints before characters

Rabin-Karp hashes the pattern and each text window of the same length. Unequal hashes prove the strings differ, so the window can be skipped immediately. Equal hashes are only a candidate match because different strings can collide.

Roll the hash as the window moves

A polynomial rolling hash removes the outgoing character's weighted contribution, shifts the remaining value by the base, and adds the incoming character. This updates the next window in O(1) time instead of hashing all m characters again.

The player scans abcabcab for cab. It displays the current window and both hashes. Hash equality triggers a character verification; successful verification records the starting index in green.

T
a
b
c
a
b
c
a
b
P
c
a
b

Hash pattern "cab" to 312, then begin with the first text window.

1function rabinKarp(text: string, pat: string): number[] {
2 const n = text.length, m = pat.length;
3 const B = 10, M = 997;
4 const val = (ch: string) => ch.charCodeAt(0) - 96;
5 let patHash = 0, winHash = 0, pow = 1;
6 for (let k = 0; k < m; k++) {
7 patHash = (patHash * B + val(pat[k])) % M; // pattern hash
8 winHash = (winHash * B + val(text[k])) % M; // first window hash
9 if (k < m - 1) pow = (pow * B) % M;
10 }
11 const res: number[] = [];
12 for (let i = 0; i + m <= n; i++) {
13 if (winHash === patHash) { // hash match
14 if (text.slice(i, i + m) === pat) { // verify characters
15 res.push(i);
16 }
17 }
18 if (i + m < n) { // rolling update O(1)
19 winHash = ((winHash - val(text[i]) * pow) * B + val(text[i + m])) % M;
20 winHash = ((winHash % M) + M) % M;
21 }
22 }
23 return res;
24}
Text Tabcabcab
Pattern Pcab
Pattern hash312
Window hash123
Matches—
1 / 12

Expected linear time with a worst-case caveat

Initial hashes cost O(m) and the scan performs O(n) rolling updates. With rare collisions, expected time is O(n + m). Repeated collisions can force O(nm) character verification, so robust implementations use large moduli, randomized bases, or double hashing.

Hash equality is never accepted as proof. Character verification keeps the algorithm correct even when collisions occur.

Compare hash-based screening with prefix reuse in KMP String Matching, then explore palindrome symmetry in Manacher's algorithm.