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.
Input: str1 = “arajjhupoot”, str2 = “rajput”
str2 can only be formed once using characters of str1.
Input: str1 = “foreeksgekseg”, str2 = “geeks”
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 str.
- 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:
Time Complexity: O(max(l1,l2)), where l1 and l2 are length of 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
- Count all sub-strings with weight of characters atmost K
- Lexicographically smallest string formed by appending a character from first K characters of a string | Set 2
- Lexicographically smallest string formed by appending a character from the first K characters of a given string
- Lexicographically smallest string formed by removing at most one character
- Count of strings that can be formed using a, b and c under given constraints
- All possible strings of any length that can be formed from a given string
- Check if given string can be formed by two other strings or their permutations
- Count of sub-strings that contain character X at least once
- Count of distinct XORs formed by rearranging two Binary strings
- Count of sub-strings that do not consist of the given character
- Longest palindromic String formed using concatenation of given strings in any order
- Find the number of strings formed using distinct characters of a given string
- Count of times second string can be formed from the characters of first string
- Pairs of strings which on concatenating contains each character of "string"
- Generate two output strings depending upon occurrence of character in input 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 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.