Find all pattern occurrences using the Rabin-Karp pattern searching algorithm.
Problem Statement
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
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
- If
m > n || m === 0, return[]. - Slide window of length
macrosstext. - Compare window against
patternand record starting indexi. - 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
Edge Cases & Corner Traps Handled
- Pattern longer than text: returns [].
- Multiple overlapping matches: "aaaaa" and "aa" -> [0, 1, 2, 3].