Check whether second string can be formed from characters of first string
You are given two strings STR1 and STR2. You need to check whether STR2 can be formed from the characters of STR1. Both the strings can contain any characters.
For example:
If STR1 = “codingninjas” and STR2 = “sing”. We can form the second string using the characters of the first string. This is because “s”, “i”, “n”, “g” are present in the string STR1.
Input Format:
The first line of input contains a single integer T, representing the number of test cases or queries to be run.
Then the T test cases follow.
The first line of each test case contains the first string STR1.
The second line of each test case contains the second string STR2.
Output Format:
For each test case, return “YES” if the second string can be formed from the characters of the first string. Otherwise, return ”NO”. (without the inverted commas)
Note:
You are not required to print the expected output, and it has already been taken care of. Just implement the function.
Constraints:
1 ≤ T ≤ 100
1 ≤ |STR1|, |STR2| ≤ 1000
Where 'T' is the number of test cases, |STR1| and |STR2| are the lengths of the strings STR1 and STR2 respectively.
Time Limit: 1 sec.
CodingNinjas
author
2y
Step 1 The idea was to count frequencies of string 1 and deduct from frequencies of string 2 simultaneously.
Step 2 If frequency at any stage becomes negative, false should be returned.
CodingNinjas
author
2y
Using Counting Array
- It can be seen from the problem that the order of the characters does not matter. Only the count of each character matters.
- All the number of characters in STR2 should be present in...read more
Help your peers!
Add answer anonymously...
Top Nagarro Technical Trainee interview questions & answers
Popular interview questions of Technical Trainee
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app