![]() |
VOOZH | about |
Given two strings str1 and str2, check if str2 can be formed from str1
Example :
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 :
Yes
Time Complexity: O(n+m), where n and m are the length of the given strings.
Auxiliary Space: O(256), which is constant.