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 :
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- 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 K palindromic strings can be formed from a given string
- Check if given string can be formed by two other strings or their permutations
- 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 whether the frequencies of all the characters in a string are prime or not
- Python | Check if frequencies of all characters of a string are different
- Check if characters of one string can be swapped to form other
- Program to check if first and the last characters of string are equal
- Check if the characters of a given string are in alphabetical order
- Check if a string is made up of K alternating characters
- Check if a given string is made up of two 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 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.