Given two strings str1 and str2, the task is to find the maximum number of times str1 occurs in str2 as a non-overlapping substring after rearranging the characters of str2
Input: str1 = “geeks”, str2 = “gskefrgoekees”
str = “geeksforgeeks”
Input: str1 = “aa”, str2 = “aaaa”
Approach: The idea is to store the frequency of characters of both the strings and comparing them.
- If there is a character whose frequency in the first string is greater than its frequency in the second string then the answer is always 0 because string str1 can never occur in str2.
- After storing the frequency of the characters of both the strings, perform integer division between the non-zero frequency of characters of str1 and str2. The minimum value would be the answer.
Below is the implementation of the above approach:
Time Complexity: O(max(M, N)) where M and N are the lengths of the given strings str1 and str2 respectively.
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Largest substring of str2 which is a prefix of str1
- Count of characters in str1 such that after deleting anyone of them str1 becomes str2
- Check whether str1 can be converted to str2 with the given operations
- Minimum cost to convert str1 to str2 with the given operations
- Generate all possible strings such that char at index i is either str1[i] or str2[i]
- First element that appears even number of times in an array
- Transform string str1 into str2 by taking characters from string str3
- Minimum number of times A has to be repeated such that B is a substring of it
- Maximum difference between two elements such that larger element appears after the smaller number
- Find if a given string can be represented from a substring by iterating the substring “n” times
- Find the only element that appears b times
- Reduce the array such that each element appears at most K times
- Remove characters from a String that appears exactly K times
- Longest subsequence where every character appears at-least k times
- Reduce the array such that each element appears at most 2 times
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.