Python Counter and Dictionary Intersection Example (Make a string using deletion and rearrangement)
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:
from collections import Counter
s1 = 'BOBthebuilder'
s2 = 'fBoOkBIHnfndBthesibuishlider'
# Count characters in both strings
count1 = Counter(s1)
count2 = Counter(s2)
# Check if all characters of str1 are present in str2
possible = True
for ch in count1:
if count1[ch] > count2[ch]:
possible = False
break
if possible:
print("Possible")
else:
print("Not Possible")
Output
Possible
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”.