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 INPUT String a = "abcd" a b c d String b = "cdabcdab" c d a b c d a b len(a) = 4 len(b) = 8 Character Sets a: {a, b, c, d} b: {a, b, c, d} Min repeats = ceil(8/4) = 2 Check up to 2+1 = 3 times ALGORITHM STEPS 1 Validate Characters Check if b chars exist in a {c,d,a,b} subset {a,b,c,d} OK 2 Try 2 Repeats "abcdabcd" "cdabcdab" not found 3 Try 3 Repeats "abcdabcdabcd" "cdabcdab" FOUND! a b c d a b c d a b c d c d a b c d a b Match at position 2 4 Return Count Found in 3 repeats Return 3 FINAL RESULT Repeated String (3 times) abcd Copy 1 abcd Copy 2 abcd Copy 3 = a b c d a b c d a b c d Contains: "cdabcdab" OK Output 3 Minimum repeats needed for b to be substring Key Insight: 1. First check if all characters in b exist in a (if not, return -1 immediately) 2. The minimum repeats needed is at least ceil(len(b)/len(a)). We only need to check at most ceil(len(b)/len(a)) + 1 times, as b could span across boundaries. TutorialsPoint - Repeated String Match | Character Set Validation + Bounded Search
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