Repeated String Match - Problem

Given two strings a and b, return the minimum number of times you should repeat string a so that string b is a substring of it.

If it is impossible for b to be a substring of a after repeating it, return -1.

Notice: string "abc" repeated 0 times is "", repeated 1 time is "abc" and repeated 2 times is "abcabc".

Input & Output

Example 1 — Basic Case
$ Input: a = "abcd", b = "cdabcdab"
Output: 3
💡 Note: We need "abcdabcdabcd" (3 repetitions) to contain "cdabcdab" as substring
Example 2 — Single Repetition
$ Input: a = "abc", b = "cab"
Output: 2
💡 Note: "abc" repeated once gives "abc", doesn't contain "cab". "abcabc" contains "cab"
Example 3 — Impossible Case
$ Input: a = "abc", b = "aabcd"
Output: -1
💡 Note: Character 'd' in b doesn't exist in a, so impossible to form b from repetitions of a

Constraints

  • 1 ≤ a.length, b.length ≤ 104
  • a and b consist of lowercase English letters

Visualization

Tap to expand
Repeated String Match Overviewa = "abc"b = "cabca"Repeat "abc" until "cabca" appears as substring"abc" ✗"abcabc" ✗"abcabcabc" ✓"cabca" found in "abcabcabc"Answer: 3 repetitions
Understanding the Visualization
1
Input
String a to repeat, string b to find
2
Process
Repeat a until b is found as substring
3
Output
Minimum repetitions needed or -1 if impossible
Key Takeaway
🎯 Key Insight: You need at most ceil(len(b)/len(a)) + 1 repetitions to find any possible substring
Asked in
Google 15 Facebook 12 Amazon 8
25.0K Views
Medium Frequency
~15 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