DSA Tracker

Medium

Rabin Karp Algorithm

A medium Strings problem included in Love Babbar 450. Below: the roles whose interviews prioritise this topic, and how to practise it.

Topic
Strings
Sheets
1
Core for
13 roles
Platform
GeeksforGeeks

The problem

Use the Rabin-Karp rolling hash technique to find all starting positions of a pattern within a text string.

Example 1

Input
text="abcabcabc", pattern="abc"
Output
[0,3,6]

Example 2

Input
text="abab", pattern="ab"
Output
[0,2]

Example 3

Input
text="hello", pattern="ll"
Output
[2]

Constraints

  • 1 <= text.length, pattern.length <= 10^4
  • strings consist of lowercase English letters

How to think about it

Updated 2026-09-09

Evaluating a rolling hash treats the sliding window as a number in a polynomial base. When the window advances one position, subtracting the departing character's highest-power contribution and shifting the rest before adding the newcomer yields the new hash in O(1). Full string character equality is only verified when two hash values actually collide.

Approaches, worst first

  1. Naive sliding window verification

    time O(n * m) · space O(1)

    Slide a window of pattern length across text and compare all characters at every offset. On adversarial inputs with heavily repetitive characters, it compares up to pattern length characters at almost every position, suffering quadratic time without hash pruning.

  2. Rolling polynomial hash with collision verificationWrite this one

    time O(n + m) · space O(1)

    Compute target hash for pattern and the initial window of text using a large prime modulus and base. Slide the window: update hash in O(1). Whenever the window hash equals pattern hash, compare the actual characters to eliminate hash collisions before adding the index to results.

Where people lose marks · 3
  • Modulo arithmetic with negative results: subtracting the departing high-order term can produce a negative value; add the modulus back before taking remainder `% MOD`.
  • Omitting character-by-character verification on hash match: spurious hash collisions lead to false positive matches unless explicitly checked.
  • Pattern longer than text: must return an empty list immediately without computing rolling hashes.

The theory behind it

Strings — the ground this problem stands on. All Strings problems

What Strings is

A string is an ordered necklace of text characters, like letters printed along a ribbon of paper. Each character sits at an exact numeric slot, holding a glyph such as a letter, punctuation mark, or digit. In many programming languages, ribbons cannot be edited after creation, meaning changing a single character requires pressing an entirely new ribbon from scratch.

When to reach for it

Reach for string techniques when inputs consist of words, DNA sequences, serialized data formats, or sentences. Clues include questions testing palindromes, anagram matches, substring patterns, parenthesis balancing, or character frequency counts. Whenever an algorithm asks to transform capitalization, parse structured tokens, or compute edits between two phrases, string representations are the core subject.

How the pattern works

Think of characters as small integer codes ranging across standard character sets. Frequency tables with fixed sizes often replace heavy hash maps when tallying occurrences. For search tasks, maintain rolling state using character indices or sliding borders. When building output text through repeated appends, accumulate pieces inside a mutable list or string builder rather than concatenating strings directly, avoiding quadratic copy overhead.

What each operation costs

OperationTime
read character by indexO(1)
concatenate two strings of total length nO(n)
compare two strings of length nO(n)
What usually goes wrong with Strings
  • Concatenating strings inside a loop using the plus operator, which silently creates full copies on each iteration and turns linear routines into quadratic slowdowns.
  • Assuming all characters fall strictly within lowercase English letters without validating spaces, uppercase variants, punctuation marks, or multi-byte unicode symbols.
  • Confusing substring length with end index when slicing, causing unexpected off-by-one truncations in languages that take length versus exclusive end position.

Which roles need this problem

Strings is a core topic for these 13 roles — if you're targeting one of them, this problem is early in your path, not optional.

Secondary for 7 more roles, including Data Engineer, Data Analyst, Embedded / Firmware Engineer.

Track this in your role's order

Pick your target role and all 370 problems — including this one — resequence to what that interview actually asks. Free.

Start free

More Strings problems

Problem set and role mapping as of .