Algo-Sim › String Algorithms

Find the Index of the First Occurrence (Rabin-Karp)

Medium · String Algorithms · step through it in Java, Python and C++ on your own input

Hash every window with a rolling hash updated in O(1) per slide, and compare letters only when the hashes agree. A tiny modulus here makes collisions visible.

Problem

Return the index where needle first occurs in haystack, or -1. This version slides a window of needle.length letters across the text, keeps a rolling hash of it, and compares letters only when the window's hash equals the pattern's.

Constraints

Edge cases to test

Follow-up questions

How do you make collisions rare?
Use a large prime modulus (about 10⁹) with a random base, or two moduli at once; then expected time is O(n + m).
Where does a rolling hash shine?
Searching many patterns of the same length, and Longest Duplicate Substring with binary search on the length (LC 1044).

Solution

Java

public int strStr(String haystack, String needle) {
    final int B = 26, M = 101;
    int n = haystack.length(), m = needle.length();
    if (m > n) return -1;
    int high = 1;
    for (int k = 1; k < m; k++) high = high * B % M;
    int target = 0, window = 0;
    for (int k = 0; k < m; k++) {
        target = (target * B + needle.charAt(k) - 'a' + 1) % M;
        window = (window * B + haystack.charAt(k) - 'a' + 1) % M;
    }
    for (int i = 0; ; i++) {
        if (window == target && haystack.startsWith(needle, i)) return i;
        if (i + m >= n) return -1;
        window = (window - (haystack.charAt(i) - 'a' + 1) * high % M + M) % M;
        window = (window * B + haystack.charAt(i + m) - 'a' + 1) % M;
    }
}

Python

def str_str(haystack, needle):
    B, M = 26, 101
    n, m = len(haystack), len(needle)
    if m > n:
        return -1
    high = pow(B, m - 1, M)
    target = window = 0
    for k in range(m):
        target = (target * B + ord(needle[k]) - 96) % M
        window = (window * B + ord(haystack[k]) - 96) % M
    for i in range(n - m + 1):
        if window == target and haystack[i:i + m] == needle:
            return i
        if i + m >= n:
            break
        window = (window - (ord(haystack[i]) - 96) * high) % M
        window = (window * B + ord(haystack[i + m]) - 96) % M
    return -1

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int strStr(string &haystack, string &needle) {
        int B = 26, M = 101;
        int n = int(haystack.size()), m = int(needle.size());
        if (m > n)
            return -1;
        int high = 1;
        for (int k = 1; k < m; k++)
            high = high * B % M;
        int target = 0, window = 0;
        for (int k = 0; k < m; k++) {
            target = (target * B + needle[k] - 'a' + 1) % M;
            window = (window * B + haystack[k] - 'a' + 1) % M;
        }
        for (int i = 0;; i++) {
            if (window == target && haystack.compare(i, m, needle) == 0)
                return i;
            if (i + m >= n)
                return -1;
            window = (window - (haystack[i] - 'a' + 1) * high % M + M) % M;
            window = (window * B + haystack[i + m] - 'a' + 1) % M;
        }
    }
};

More String Algorithms problems