VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-of-strings-that-can-be-formed-from-another-string-using-each-character-at-most-once/

⇱ Count of strings that can be formed from another string using each character at-most once - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count of strings that can be formed from another string using each character at-most once

Last Updated : 22 Nov, 2022

Given two strings str1 and str2, the task is to print the number of times str2 can be formed using characters of str1. However, a character at any index of str1 can only be used once in the formation of str2

Examples:  

Input: str1 = "arajjhupoot", str2 = "rajput" 
Output:
Explanation:
str2 can only be formed once using characters of str1.

Input: str1 = "foreeksgekseg", str2 = "geeks" 
Output: 2

Approach: 

Since the problem has a restriction on using characters of str1 only once to form str2. If one character has been used to form one str2, it cannot be used in forming another str2. Every character of str2 must be present in str1 at least for the formation of one str1. If all the characters of str2 are already present in str1, then the character which has the minimum occurrence in str1 will be the number of str2's that can be formed using the characters of str1 once. Below are the steps: 

  • Create an hash-array which stores the number of occurrences of each character of str1 and str2.
  • Iterate for all the characters of str2, and find the minimum most occurrences of every character in str1.
  • Return the minimum occurrence which will be the answer.

Below is the implementation of the above approach: 


Output
2

Complexity Analysis:

  • Time Complexity: O(l1+l2), where l1 and l2 are length of str1 and str2 respectively. 
  • Auxiliary Space: O(1)

Case: Using STL Maps with both uppercase and lowercase characters in str1 and str2.

Approach: 

The operation is similar to the normal hash-array.

Here, the order does not matter. We just need to check if there are sufficient words in str1 to make str2. Traverse both strings str1 and str2 to store characters as key and their frequencies as value in maps freq1 and freq2. Divide the frequencies stored in map freq1 with frequencies that have a matching key in map freq2

This will give us the maximum number of cycles of str2 that can be formed. Finally return minimum frequency from map freq1 which will be the final answer.

Implementation:


Output
1

Complexity Analysis:

  • Time Complexity: O(l1+l2), where l1 and l2 are length of str1 and str2 respectively
  • Auxiliary Space: O(1) since the total number of distinct characters in both lowercase and uppercase English alphabets is 52 (Constant).
Comment