Repeated String Match

Given two strings a and b, return the minimum number of times a has to be repeated so that b becomes a substring of the repeated string. If that is impossible, return -1. Repeating "abc" 0 times gives "", once gives "abc", twice gives "abcabc".

30:00

Repeated String Match
medium
Free written solution
Topics
Companies

Given two strings a and b, return the minimum number of times a has to be repeated so that b becomes a substring of the repeated string. If that is impossible, return -1. Repeating "abc" 0 times gives "", once gives "abc", twice gives "abcabc".

Example 1:
Input: {"a":"abcd","b":"cdabcdab"}
Output: 3
Constraints:
  • 1≤a.length,b.length≤1041 \leq a.\text{length}, b.\text{length} \leq 10^4

  • a and b consist of lowercase English letters.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"a":"abcd","b":"cdabcdab"}

Start with one copy of a (length 4). b has length 8, so we need at least enough copies to cover 8 characters.

a =

"abcd"

count =

1

len(built) =

4

len(b) =

8

built = a repeated 1 time, b slides underneath

copy 1

a
b
c
d
c
d
a
b
c
d
a
b

b (sticks out: built is still too short)

copies of a

spare copy

matched

mismatch

Variables
VariableValue
count1
len(built)4
len(b)8
DepthFunction Call
Stack empty
0/8