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: a = "abcd", b = "cdabcdab"
Output: 3
Explanation: We return 3 because by repeating a three times "abcdabcdabcd", b is a substring of it.
Input: a = "a", b = "aa"
Output: 2
Constraints:
a and b consist of lowercase English letters.The problem requires us to determine the minimum number of times string A has to be repeated such that B is a substring of it. A brute force solution involves repeatedly appending A to itself until B becomes a substring or we surpass a certain reasonable limit.
A is at least |B|/|A| (integer division) and at most |B|/|A| + 2.B can start appearing mid-way within one of the copies of A which might require one or two more copies of A to cover whole of B.A, and keep appending A to this string.B is a substring of the current repeated string.B is found, return the count of repetitions. If after |B|/|A| + 2 repetitions B is not found, return -1.N is the length of A and M is the length of B. This is due to the substring search operation.The brute force solution already works fairly efficiently for most reasonable input sizes. However, we can optimize the repeated string construction and search process slightly using intuitive bounds.
ceil(|B|/|A|), which can be done using (B.length() + A.length() - 1) / A.length().A to handle boundary conditions.B is a substring after minRepeats and minRepeats + 1 repetitions and return the respective count if true.B is not a substring in both checks.N is the length of A and M is the length of B. This comes from building the string and subsequent substring check.