Problem 714
Repeated String Match
Medium · 20 pts · String, String Matching, Rolling Hash
Problem
Find the minimum number of times string A must be repeated (written one copy after another) so that string B becomes a substring of the result, or print -1 if that is impossible. Repeating A q = ceil(|B| / |A|) times gives a string at least as long as B; if B is not inside q or q + 1 copies of A, more copies cannot help, because any match would already start inside the first copy. Test each candidate with a linear-time search such as Rabin-Karp or KMP.
Input
The first line contains A. The second line contains B. Both use lowercase letters.
Output
Print the minimum number of repetitions, or -1.
Constraints
1 <= |A|, |B| <= 10000
Example input
abcd cdabcdab
Example output
3
Explanation
With A = abcd and B = cdabcdab, three copies give abcdabcdabcd, which contains cdabcdab starting at index 2. Two copies (abcdabcd) are too short, so the answer is 3.