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 31 and modulus 10^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
INPUTALGORITHMRESULTText: "abcabcab"abcabcaPattern: "abc"abcFind all positions wherepattern matches in text1Calculate pattern hashhash('abc') = 31² × a + 31¹ × b + c2Slide window with rolling hashUpdate hash: remove left, add right3Compare hashesIf equal, verify with string match4Collect all match positionsStore indices where pattern foundMatches Found:[0, 3]Position 0: "abc"abcabPosition 3: abc"abc"abRolling hash found2 occurrences efficientlyKey Insight:Rolling hash allows O(1) hash updates as we slide the window, making string search O(n+m) instead of O(n×m)TutorialsPoint - Rabin-Karp String Search | Rolling Hash Algorithm
Asked in
Google 45 Amazon 38 Microsoft 32 Facebook 28
23.5K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen