Rabin Karp Rolling Hash Pattern Match (Java)
Find all occurrences of a pattern in Java text using Rabin Karp with a rolling hash for O(n+m) average time.
Code
import java.util.*;
public class RabinKarp {
public static List<Integer> search(String text, String pattern) {
int base = 256, mod = 101, n = text.length(), m = pattern.length();
if (m == 0 || m > n) return List.of();
int patH = 0, txtH = 0, h = 1;
for (int i = 0; i < m - 1; i++) h = (h * base) % mod;
for (int i = 0; i < m; i++) { patH = (patH * base + pattern.charAt(i)) % mod; txtH = (txtH * base + text.charAt(i)) % mod; }
List<Integer> result = new ArrayList<>();
for (int i = 0; i <= n - m; i++) { if (patH == txtH && text.substring(i, i + m).equals(pattern)) result.add(i); if (i < n - m) { txtH = (base * (txtH - text.charAt(i) * h) + text.charAt(i + m)) % mod; if (txtH < 0) txtH += mod; } }
return result;
}
}How the snippet works
Count the class RabinKarp and the function search as the entire surface area of Rabin Karp Rolling Hash Pattern Match (Java).
Iteration happens inside for (int i = 0; i < m - 1; i++) h = (h * base) % mod; — everything outside it runs once.
Applying it
Signature: public static List<Integer> search(String text, String pattern)
Statements that matter
if (m == 0 || m > n) return List.of();
Interactive Tools for This Topic
SHA-256 Hash GeneratorGenerate SHA-256 cryptographic hashes from text input using the Web Crypto API. Compare hashes and verify data integrity with hexadecimal digest output.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Webhook HMAC Signature VerifierVerify and generate HMAC-SHA256 webhook signatures for Stripe, GitHub, and raw hex headers locally using Web Crypto and constant-time comparison.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.
FAQ
- Is there an install step between copy and run?
- No. Between copying and running there is nothing left to do. The file defines `search` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.