Rabin-Karp String Search - Problem
Implement the Rabin-Karp string matching algorithm using polynomial rolling hash to find all occurrences of a pattern string in a text string.
The Rabin-Karp algorithm uses hashing to find any one of a set of pattern strings in a text. It uses a rolling hash to quickly filter out positions of the text that cannot match the pattern, and then checks for a match at the remaining positions.
For this implementation:
- Use a polynomial rolling hash with base
31and modulus10^9 + 7 - Return a list of all starting indices where the pattern occurs in the text
- If no matches are found, return an empty list
Note: The algorithm should handle hash collisions by verifying actual string matches when hashes are equal.
Input & Output
Example 1 — Basic Pattern Match
$
Input:
text = "abcabcab", pattern = "abc"
›
Output:
[0,3]
💡 Note:
Pattern 'abc' appears at index 0 ('abc'abcab) and index 3 (abc'abc'ab). The rolling hash quickly identifies these positions.
Example 2 — Single Character Pattern
$
Input:
text = "aaaaa", pattern = "a"
›
Output:
[0,1,2,3,4]
💡 Note:
Single character 'a' appears at every position in the text. Rolling hash efficiently processes each position.
Example 3 — No Match Found
$
Input:
text = "hello", pattern = "world"
›
Output:
[]
💡 Note:
Pattern 'world' does not exist anywhere in text 'hello', so return empty array.
Constraints
- 1 ≤ text.length ≤ 105
- 1 ≤ pattern.length ≤ 103
- text and pattern consist of lowercase English letters only
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code