Member-only story
Coding problem: Anagram difference
I was given this problem in an online coding assessment
Problem description
An anagram is a word whose characters can be rearranged to create another word. Given two strings, determine the minimum number of characters in either string that must be modified to make the two strings anagrams. If it is not possible to make the two strings anagrams, return -1.
Constraints:
- Each string consists of lowercase letters [a-z].
- 0 ≤ |S1|, |S2| ≤ 10⁴
Example
S1 = “tea” and S2 = “ate” are anagrams. So 0 characters need to be modified.
S1 = “tea” and S2 = “toe” are not anagrams. Modify 1 character in either string (o -> a or a -> o) to make them anagrams.
Solution approach
One trivial case that needs to be handled separately which is: unequal string length of S1 and S2. In this case, no amount of modification would make both strings equal. So the answer would be -1. And this is the only case where the answer would be -1.
For any other cases, my approach is to first calculate the frequency of characters in both strings and store them in two separate maps/dictionaries. Now we have to compare two maps for the frequencies of each of the 26 alphabetic characters. For every occurrence of a character in both strings we can make a potential match between both occurrences. For this…











