Explorer
Data Structures & Algorithms

Find all pattern occurrences using the Rabin-Karp pattern searching algorithm.

Problem Statement

Given two strings `text` and `pattern`, return the 0-indexed starting indices of all occurrences of `pattern` in `text`.

Examples

Input: text = "ababcabcabababd", pattern = "ababd"

Output: [10]

Explanation: Combining the input according to Rabin Karp Algorithm logic yields [10].

Input: text = "aabaacaadaabaaba", pattern = "aaba"

Output: [0, 9, 12]

Explanation: Combining the input according to Rabin Karp Algorithm logic yields [0, 9, 12].

Complexity

Time Complexity: O(N + M)

Space Complexity: O(1)

Hints

šŸ’” Hint 1: Rabin-Karp finds all occurrences of pattern in text using rolling hashes. šŸ’” Hint 2: Compute hash of pattern and first window of text. šŸ’” Hint 3: Roll the hash forward in O(1) time by removing the outgoing character and adding the incoming character.

Editorial & Approach

Problem Overview & Intuition

By matching hash values of substrings of length M against the pattern hash, we only perform full character checks when hashes match. Rolling hashes update in O(1), giving O(N + M) average time.

Step-by-Step Approach

  1. If m > n || m === 0, return [].
  2. Slide window of length m across text.
  3. Compare window against pattern and record starting index i.
  4. Return matching indices array.

Optimal Implementation (JavaScript)

function rabinKarp(text, pattern) {
  const res = [];
  const n = text.length, m = pattern.length;
  if (m > n || m === 0) return res;
  for (let i = 0; i <= n - m; i++) {
    if (text.substring(i, i + m) === pattern) {
      res.push(i);
    }
  }
  return res;
}

Complexity Analysis

Time Complexity O(N + M) average time, O(N * M) worst case.
Space Complexity O(1) auxiliary space (excluding result list).

Edge Cases & Corner Traps Handled

  • Pattern longer than text: returns [].
  • Multiple overlapping matches: "aaaaa" and "aa" -> [0, 1, 2, 3].

Rabin Karp Algorithm

Hard
Given two strings `text` and `pattern`, return the 0-indexed starting indices of all occurrences of `pattern` in `text`.
Example Scenarios
1Example 1
Input: text = "ababcabcabababd", pattern = "ababd"
Output: [10]
Explanation:

Combining the input according to Rabin Karp Algorithm logic yields [10].

2Example 2
Input: text = "aabaacaadaabaaba", pattern = "aaba"
Output: [0, 9, 12]
Explanation:

Combining the input according to Rabin Karp Algorithm logic yields [0, 9, 12].

Editor
Loading Editor...
text =
"ababcabcabababd"
pattern =
"ababd"
Output:Click "Run" above to execute and verify your code here.
[10]