Given two strings, check if it is possible to make the first string from the second by deleting some characters from the second string and rearranging the remaining characters.
Examples:
Input : s1 = BOBthebuilder
: s2 = fBoOkBIHnfndBthesibuishlider
Output : Possible
Input : s1 = Hello
: s2 = dnaKfhelddf
Output : Not Possible
Approach:
1. Count each character in both strings
- We use Python’s Counter from the collections module.
- Counter(str1) gives a dictionary-like object showing how many times each character appears in str1.
- Similarly, Counter(str2) counts characters in str2.
2. Compare character counts
- For each character in str1, we check if str2 has that character in equal or greater quantity.
- Example:
- If str1 needs 2 'A's, then str2 must have at least 2 'A's.
- If even one character from str1 is missing or appears fewer times in str2, then the answer is “Not Possible.”
3. Decide the result
- If all characters in str1 are found in sufficient quantity in str2, print “Possible.”
- Otherwise, print “Not Possible.”
Implementation:
Explanation:
- We use Counter to count how many times each character appears.
- Then we check, one by one, if str2 has enough of each character.
- If any character is missing or fewer, it prints “Not Possible”.
- Otherwise, it prints “Possible”.
Related Articles: