VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-number-of-times-str1-appears-as-a-non-overlapping-substring-in-str2/

⇱ Maximum number of times str1 appears as a non-overlapping substring in str2 - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum number of times str1 appears as a non-overlapping substring in str2

Last Updated : 22 Jun, 2022

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

Input: str1 = "geeks", str2 = "gskefrgoekees" 
Output:
str = "geeksforgeeks"
Input: str1 = "aa", str2 = "aaaa" 
Output:
 


 


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: 
 


Output: 
2

 

Time Complexity: O(max(M, N)), as we using a loop to traverse N times and M times. Where M and N are the lengths of the given strings str1 and str2 respectively.
Auxiliary Space: O(26), as we are using extra space for the map.

Comment