oneby7

String Matching Pattern matching

582. Repeated String Match

Medium

You are given two strings, a and b. Write a out several times in a row, with nothing between the copies. Return the smallest number of copies that makes b appear in the result, or -1 if no number of copies does.

b appears in a string when its letters show up there in order and next to each other. For example, three copies of "ab" give "ababab", and "bab" appears in it.

Example 1

Input: a = "xyz", b = "zxyzx"

Output: 3

Explanation: Two copies give xyzxyz. That is long enough, but zxyzx does not appear in it. Three copies give xyzxyzxyz, and zxyzx starts at index 2.

Example 2

Input: a = "ab", b = "bb"

Output: -1

Explanation: Every b in the copies is followed by an a, so two b letters never sit next to each other.

Example 3

Input: a = "hello", b = "ohe"

Output: 2

Explanation: b is shorter than a, but it runs across the join of two copies: hellohello has ohe at index 4.

Check your understanding

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

a = "abc", b = "cabca"

Constraints

  • 1 ≤ a.length, b.length ≤ 105
  • a and b 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.