Given two strings A and B. The task is to find the minimum number of times A has to be repeated such that B is a substring of it. If no such solution exsits print -1.
Input : A = “abcd”, B = “cdabcdab”
Output : 3
Repeating A three times (“abcdabcdabcd”), B is a substring of it. B is not a substring of A when it is repeated less than 3 times
Input : A = “ab”, B = “cab”
Output : -1
Imagine we wrote S = A+A+A+… If B is a substring of S, we only need to check whether some index 0 or 1 or …. length(A) -1 starts with B, as S is long enough to contain B, and S has a period of length(A).
Now, suppose ans is the least number for which length(B) <= length(A * ans). We only need to check whether B is a substring of A * ans or A * (ans+1). If we try k < ans, then B has larger length than A * ans and therefore can’t be a substring. When k = ans+1, A * k is already big enough to try all positions for B( A[i:i+length(B)] == B for i = 0, 1, …, length(A) – 1).
Below is the implementation of the above approach :
- Number of subsequences as "ab" in a string repeated K times
- Maximum number of times str1 appears as a non-overlapping substring in str2
- Find if a given string can be represented from a substring by iterating the substring “n” times
- String which when repeated exactly K times gives a permutation of S
- Largest element in the array that is repeated exactly k times
- Longest sub string of 0's in a binary string which is repeated K times
- Check if any permutation of string is a K times repeated string
- Minimum steps to delete a string after repeated deletion of palindrome substrings
- Minimum length substring with exactly K distinct characters
- Minimum K such that every substring of length atleast K contains a character c
- Minimum characters to be replaced to remove the given substring
- Minimum splits in a binary string such that every substring is a power of 4 or 6.
- Minimum steps to remove substring 010 from a binary string
- N/3 repeated number in an array with O(1) space
- Remove repeated digits in a given number
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.