Open In App

Check whether second string can be formed from characters of first string

Last Updated : 29 Sep, 2022
Comments
Improve
Suggest changes
8 Likes
Like
Report

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 : 

C++
Java Python3 C# PHP JavaScript

Output
Yes

Time Complexity: O(n+m), where n and m are the length of the given strings. 
Auxiliary Space: O(256), which is constant.


Next Article

Similar Reads