Strings & Compression Hard
Rabin-Karp Multi-Pattern Search
Rabin–Karp hashes equal-length patterns into a table, then rolls one fixed-width hash over the text and verifies hash hits with string equality.
Trace input
Bounded JSONEdit the lesson input, then build a deterministic source-linked trace.
Source scenarios
Complexity
BestO(PM + N + C·M)
AverageO(PM + N + C·M)
WorstO(PM + NM)
SpaceO(P + M)
Array state
Follow the active comparisons and writes.
Current operation
Trace stateReady to explore
Source behavior & common mistakes
Return the starting index of the first text window matching any pattern. If none match, return the text length, as the pinned Java implementation does.
- All patterns must have the same UTF-16 length because the constructor takes M from pat[0] and hashes every pattern using that M.
- The source uses radix 2048 and modulus 4463, not the more common radix 256 or 31.
- Hashtable.put overwrites earlier patterns when their hashes collide; only the most recently stored pattern for that hash is checked.
- A matching hash is only a candidate: check compares the stored pattern with the exact substring to reject false positives.
- Java String.length, charAt, and substring use UTF-16 code-unit indices; the result for no match is that code-unit length.
- The source hashes the first M text units immediately and throws if text is shorter than M; the lesson rejects that input before tracing.
Algorithm code
JavaRabinKarp.javaStep linked
The highlighted line follows the current step.
Ready to begin
Press Play to see what happens.
Detailed execution
Snapshot 1 / 1