Rabin Karp Rolling Hash Pattern Match (Go)
Find all occurrences of a pattern in Go text using Rabin Karp with a rolling hash for O(n+m) average time.
Code
package main
func rabinKarp(text, pattern string) []int {
base, mod := 256, 101
n, m := len(text), len(pattern)
if m == 0 || m > n { return nil }
patHash, txtHash, h := 0, 0, 1
for i := 0; i < m-1; i++ { h = (h * base) % mod }
for i := 0; i < m; i++ { patHash = (patHash*base + int(pattern[i])) % mod; txtHash = (txtHash*base + int(text[i])) % mod }
var result []int
for i := 0; i <= n-m; i++ {
if patHash == txtHash && text[i:i+m] == pattern { result = append(result, i) }
if i < n-m { txtHash = (base*(txtHash-int(text[i])*h) + int(text[i+m])) % mod; if txtHash < 0 { txtHash += mod } }
}
return result
}What the code does
Rabin Karp Rolling Hash Pattern Match (Go) keeps everything in the function rabinKarp.
Repetition is confined to for i := 0; i < m-1; i++ { h = (h * base) % mod } — the rest of the file is straight-line.
Applying it
Entry signature: func rabinKarp(text, pattern string) []int
Statements that matter
if i < n-m { txtHash = (base*(txtHash-int(text[i])*h) + int(text[i+m])) % mod; if txtHash < 0 { txtHash += mod } }
if patHash == txtHash && text[i:i+m] == pattern { result = append(result, i) }
if m == 0 || m > n { return nil }
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
- Does this work in a bare project with no dependencies file?
- Yes — a bare project runs it as-is, since nothing needs declaring. The file defines `rabinKarp` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.