Given two strings str1 and str2, check if str2 can be formed from str1
Input : str1 = geekforgeeks, str2 = geeks Output : Yes Here, string2 can be formed from string1. Input : str1 = geekforgeeks, str2 = and Output : No Here string2 cannot be formed from string1. Input : str1 = geekforgeeks, str2 = geeeek Output : Yes Here string2 can be formed from string1 as string1 contains 'e' comes 4 times in string2 which is present in string1.
The idea is to count frequencies of characters of str1 in a count array. Then traverse str2 and decrease frequency of characters of str2 in the count array. If frequency of a characters becomes negative at any point, return false.
Below is the implementation of above approach :
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
- Check if a given string can be formed using characters of adjacent cells of a Matrix
- 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
- Count of times second string can be formed from the characters of first string
- Check if a string can be formed from another string by at most X circular clockwise shifts
- Lexicographically largest string formed from the characters in range L and R
- Find the number of strings formed using distinct characters of a given string
- Check if given string can be formed by two other strings or their permutations
- Check if K palindromic strings can be formed from a given string
- Check whether a binary string can be formed by concatenating given N numbers sequentially
- Quick way to check if all the characters of a string are same
- Check if both halves of the string have same set of characters
- Check if a given string is made up of two alternating characters
- Check if a string is made up of K alternating characters
- Check if both halves of the string have same set of characters in Python
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.