Input: str1 = "bcadeh" str2 = "hea" Output: 3 We need to remove b, c and d from str1. Input: str1 = "cddgk" str2 = "gcd" Output: 2 Input: str1 = "bca" str2 = "acb" Output: 0
This problem has an existing solution, please refer to the section Counter () and Dictionary Data Structure, and the intersection property of the Set data structure. The approach is very simple,
- Convert each line to a dictionary data structure using the Counter (iterable) method.
- Count the number of keys in both dictionaries ( count1, count2) and count the number of keys common in both dictionaries.
- If no shared keys are found, this means we need to remove the count1 + count2 characters from both strings.
- Else (max (count1, count2) — countCommon) will be the number of characters to be removed
# The function removes the minimum number of characters so that
# two lines become an anagram
removeChars (str1, str2):
# make dictionaries from both strings
# extract keys from dict1 and dict2
dict1 .keys ()
# number of keys in both keylists
# convert a list of keys in a set to find shared keys
(set1.intersection ( keys2))
# Driver program
removeChars (str1, str2)