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 :
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- 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
- Number of times Maximum and minimum value updated during traversal of array
- Minimum number of steps needed to remove the substring K from given string
- Minimum length of substring whose rotation generates a palindromic substring
- Largest substring where all characters appear at least K times | Set 2
- Check if given string is a substring of string formed by repeated concatenation of z to a
- Check if any permutation of string is a K times repeated string
- Longest sub string of 0's in a binary string which is repeated K times
- Minimum steps to delete a string after repeated deletion of palindrome substrings
- 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 length substring with exactly K distinct characters
- Remove repeated digits in a given number
- N/3 repeated number in an array with O(1) space
- 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
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.