Strings: Making Anagrams

Strings: Making Anagrams

Alice is taking a cryptography class and finding anagrams to be very useful. We consider two strings to be anagrams of each other if the first string’s letters can be rearranged to form the second string. In other words, both strings must contain the same exact letters in the same exact frequency For example, bacdc and dcbac are anagrams, but bacdc and dcbad are not.

Alice decides on an encryption scheme involving two large strings where encryption is dependent on the minimum number of character deletions required to make the two strings anagrams. Can you help her find this number?

Given two strings, $a$ and $b$, that may or may not be of the same length, determine the minimum number of character deletions required to make $a$ and $b$ anagrams. Any characters can be deleted from either of the strings.

Input Format
  • The first line contains a single string, $a$.
  • The second line contains a single string, $b$.
Constraints
  • $1 \le |a|, |b| \le 10^4$
  • It is guaranteed that $a$ and $b$ consist of lowercase English alphabetic letters (i.e., $a$ through $z$).
Output Format

Print a single integer denoting the number of characters you must delete to make the two strings anagrams of each other.

Sample Input

cde

abc

Sample Output

4

Explanation

We delete the following characters from our two strings to turn them into anagrams of each other:
Remove d and e from cde to get c.
Remove a and b from abc to get c.
We must delete 4 characters to make both strings anagrams, so we print 4 on a new line.

My Answer Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
def number_needed(a, b):

def make_dict(string):
dic = {}
for char in string:
if char in dic:
dic[char] += 1
else:
dic[char] = 1
return dic

dic_a = make_dict(a)
dic_b = make_dict(b)

common_chars = list(dic_a.keys() & dic_b.keys())

if not common_chars:
return 'anagrams cannot be made out of these set of strings'

stay_char = 0
for char in common_chars:
stay_char += min(dic_a[char], dic_b[char])

return len(a) + len(b) - (stay_char * 2)

Testing

1
2
3
a = 'cde'
b = 'abc'
number_needed(a, b)
1
4
1
2
3
a = 'a'
b = 'c'
number_needed(a, b)
1
'anagrams cannot be made out of these set of strings'
1
2
3
a = 'bacdc'
b = 'dcacb'
number_needed(a, b)
1
0
Share