Problem Description
Given two strings a and b, determine the minimum number of times a must be repeated such that b becomes a substring of the repeated a. If b can never be a substring, return -1.
Key Insights
- The key observation is that b will be found within the repeated string a after a sufficient number of repeats, possibly spanning the junction between two copies of a.
- The initial number of repeats can be approximated by ceiling(|b| / |a|). To handle potential overlaps at the boundaries, one additional repetition might be necessary.
- A simple check using built-in substring methods is sufficient to verify if b is contained in the repeated string.
Space and Time Complexity
Time Complexity: O(n * k), where n is the length of a and k is the minimum number of repeats (usually a small constant in practice). Space Complexity: O(n * k), which is the space required to construct the repeated string.
Solution
The solution calculates an initial repeat count using the ceiling of the division of b's length by a's length. It then constructs a repeated version of a and checks if b is a substring. Because b could span across the boundary of two adjacent a's, the solution appends one more repetition of a if necessary. If b is still not found, return -1.