oneby7

String Matching Pattern matching

580. Rabin-Karp

Medium

You are given two strings, pattern and text. Return every index of text where pattern appears, from smallest to largest. If pattern does not appear, return an empty list.

pattern appears at index i when the letters of text from index i on spell out pattern, in order and next to each other. Indexes start at 0. Two appearances may overlap, and each one counts.

Example 1

Input: pattern = "aba", text = "abacabababa"

Output: [0,4,6,8]

Explanation: aba starts at indexes 0, 4, 6 and 8. The last three overlap: each one shares its first a with the end of the one before.

Example 2

Input: pattern = "xyz", text = "xyxzyz"

Output: []

Explanation: xy and yz both appear, but never with the third letter next to them, so xyz does not appear.

Example 3

Input: pattern = "rotor", text = "rotor"

Output: [0]

Explanation: pattern is the whole of text, so its only appearance starts at index 0.

Check your understanding

Work out the answer for this input before you write any code.

pattern = "aba", text = "ababa"

Constraints

  • 1 ≤ pattern.length ≤ text.length ≤ 106
  • pattern and text hold only lowercase English letters.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.