Rabin Karp Rolling Hash Pattern Match (Rust)

Find all occurrences of a pattern in Rust text using Rabin Karp with a rolling hash for O(n+m) average time.

RustData Fetching

Code

rustsnippet
12 lines
fn rabin_karp(text: &str, pattern: &str) -> Vec<usize> {
    let (base, mod_): (i64, i64) = (256, 101);
    let t: Vec<u8> = text.bytes().collect(); let p: Vec<u8> = pattern.bytes().collect();
    let (n, m) = (t.len(), p.len());
    if m == 0 || m > n { return vec![]; }
    let mut pat_h = 0i64; let mut txt_h = 0i64; let mut h = 1i64;
    for _ in 0..m-1 { h = (h * base) % mod_; }
    for i in 0..m { pat_h = (pat_h * base + p[i] as i64) % mod_; txt_h = (txt_h * base + t[i] as i64) % mod_; }
    let mut result = vec![];
    for i in 0..=n-m { if pat_h == txt_h && &t[i..i+m] == &p[..] { result.push(i); } if i < n-m { txt_h = (base * (txt_h - t[i] as i64 * h) + t[i+m] as i64) % mod_; if txt_h < 0 { txt_h += mod_; } } }
    result
}

What the code does

Rabin Karp Rolling Hash Pattern Match (Rust) reduces to the function rabin_karp.

Iteration happens inside for _ in 0..m-1 { h = (h * base) % mod_; } — everything outside it runs once.

Applying it

The main signature reads fn rabin_karp(text: &str, pattern: &str) -> Vec<usize>

The surface worth importing is rabin_karp; the helpers around it are private to the snippet.

Statements that matter

let t: Vec<u8> = text.bytes().collect(); let p: Vec<u8> = pattern.bytes().collect();
if m == 0 || m > n { return vec![]; }

Interactive Tools for This Topic

FAQ

Does this require external packages?
No. It relies only on built-in language and platform APIs, so you can paste it into a project without installing anything. The file defines `rabin_karp` at load time.