08. Minimum Repeats to Make Substring
The problem can be found at the following link: Problem Link
Problem Description
Given two strings s1 and s2, return the minimum number of times s1 has to be repeated so that s2 becomes a substring of the repeated s1. If s2 cannot be a substring of any repeated version of s1, return -1.
Examples:
Input:
s1 = "ww", s2 = "www"Output:
2Explanation: Repeating s1 two times ("wwww"), s2 is a substring of it.
Input:
s1 = "abcd", s2 = "cdabcdab"Output:
3Explanation: Repeating s1 three times ("abcdabcdabcd"), s2 is a substring. Less than 3 repeats would not contain s2.
Input:
s1 = "ab", s2 = "cab"Output:
Explanation: No matter how many times s1 is repeated, s2 can’t be a substring.
Constraints:
1 ≤ |s1|, |s2| ≤ 10^5
My Approach
Repeated Concatenation Check:
Initialize a repeated version of
s1and keep appendings1to it until its length meets or exceedss2’s length.After each append, check if
s2becomes a substring of this extendeds1.If it does, return the number of repetitions used.
Pattern Matching with KMP Algorithm:
Use the KMP (Knuth-Morris-Pratt) algorithm to efficiently search for
s2within the extended repeated string ofs1.The
LPS(Longest Prefix Suffix) array is computed fors2to enable efficient substring search.
Edge Cases:
If
s1is already a substring ofs2, return the number of repetitions found.If no valid repetition count satisfies the substring condition, return
-1.
Time and Auxiliary Space Complexity
Expected Time Complexity: O(n + m), where
nis the length ofs1andmis the length ofs2. This is because the KMP algorithm requires linear time to find a substring.Expected Auxiliary Space Complexity: O(m), as we need additional space to store the
LPSarray fors2.
Code (C++)
Code (Java)
Code (Python)
Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!
⭐ If you find this helpful, please give this repository a star! ⭐
📍Visitor Count
Last updated