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:

2

Explanation: Repeating s1 two times ("wwww"), s2 is a substring of it.

Input:

s1 = "abcd", s2 = "cdabcdab"

Output:

3

Explanation: 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

  1. Repeated Concatenation Check:

    • Initialize a repeated version of s1 and keep appending s1 to it until its length meets or exceeds s2’s length.

    • After each append, check if s2 becomes a substring of this extended s1.

    • If it does, return the number of repetitions used.

  2. Pattern Matching with KMP Algorithm:

    • Use the KMP (Knuth-Morris-Pratt) algorithm to efficiently search for s2 within the extended repeated string of s1.

    • The LPS (Longest Prefix Suffix) array is computed for s2 to enable efficient substring search.

  3. Edge Cases:

    • If s1 is already a substring of s2, 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 n is the length of s1 and m is the length of s2. 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 LPS array for s2.

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