Hackerrank - Making Anagrams Solution
1 min read

Hackerrank - Making Anagrams Solution

Hackerrank - Making Anagrams Solution

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 is taking a cryptography class and finding anagrams to be very useful. She 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,  and , that may not be of the same length, determine the minimum number of character deletions required to make  and  anagrams. Any characters can be deleted from either of the strings.

For example,  and . The only characters that match are the 's so we have to remove  from  and  from  for a total of  deletions.

Function Description

Complete the makingAnagrams function in the editor below. It should return an integer representing the minimum number of deletions needed to make the strings anagrams.

makingAnagrams has the following parameter(s):

  • s1: a string
  • s2: a string

Input Format

The first line contains a single string, .
The second line contains a single string, .


  • It is guaranteed that  and  consist of lowercase English letters, ascii[a-z].

Output Format

Print a single integer denoting the minimum number of characters which must be deleted to make the two strings anagrams of each other.

Sample Input


Sample Output



We delete the following characters from our two strings to turn them into anagrams of each other:

  1. Remove d and e from cde to get c.
  2. Remove a and b from abc to get c.

We had to delete  characters to make both strings anagrams.

Solution in Python

from collections import Counter
def makingAnagrams(s1, s2):
    return len(s1)+len(s2)-sum((Counter(s1) & Counter(s2)).values())*2
print(makingAnagrams(input(), input()))

Enjoying these posts? Subscribe for more

Adblocker detected! Please consider reading this notice.

We've detected that you are using AdBlock Plus or some other adblocking software which is preventing the page from fully loading.

That's okay. But without advertising-income, we can't keep making this site awesome.

We don't have any banner, Flash, animation, obnoxious sound, or popup ad. We do not implement these annoying types of ads!

We need money to operate the site, and almost all of it comes from our online advertising.

Please add thepoorcoder.com to your ad blocking whitelist or disable your adblocking software.