Given two strings, check if the second string can be constructed from characters of the first string, where each character of the first string can be used only once in the second string.

For example,

Input: first = abc, second = ab
Output: true
 
Input: first = ab, second = abb
Output: false

 
We can use the hashing technique to solve this problem. The idea is to find the frequency of each character in the first string and store it in a hash table. Now, for each character of the second string, decrease its count in the hash table. If at some point the count becomes negative, we can say that the second string cannot be constructed from the first string.

Following is the C, C++, Java, and Python implementation based on the idea:

C


Download  Run Code

Output:

true

C++


Download  Run Code

Output:

true

Java


Download  Run Code

Output:

true

Python


Download  Run Code

Output:

True

The time complexity of the above solution is O(n) and requires O(n) extra space, where n is the length of the string.