Minimum Number of Steps to Make Two Strings Anagram

Concepts Used

Strings, Hashing

Difficulty Level


Problem Statement (Simplified):

For given two string, Print minimum number of steps to make them anagram.

See original problem statement here

Test Case

expertcoder zenithcoder


In 'expertcoder' and 'zenithcoder', 7 characters ('e','t','c','o','d','e','r') are common in both. 

Characters which are not common are :
In 'expertcoder' : 'e','x','p','r'
In 'zenithcoder' : 'z','n','i','h'

If we convert, 'e' to 'z', 'x' to 'n', 'p' to 'i' and 'r' to 'h', both strings becomes Anagram.

Solving Approach :

> Anagram: Two strings are anagram if both of them contain the same characters with a different arrangement. For example prepbytes and bytesprep are anagrams according to data structures in java.
> 1) We can count a minimum number of changes if we can find if how many numbers of characters are different in one string from another string. We do it for both of the strings.
> 2) We check this by scanning both strings, and increase value by 1 for the current character in 1^{st} string and decrease the value by 1 for the current character in 2^{nd} string.
> 3) After scanning both strings, we find the absolute sum of the hash table where sum represents the number of characters different in both strings.
> 2) After checking this out, we know a single change would affect two characters, if we change one character to another one which is extra in second string and missing in the first string.
> 3) So we print half of that sum as our answer.


  • Lets assume two strings to be ‘prepbuddy‘ and ‘codepuddy‘.

  • As we defined in the definition of anagram, two strings must have the same number of characters in any order. So we first find the number of characters which are different in both strings.

  • We can calculate such characters using a hash table.

  • After scanning both strings our hash table becomes

  • 1 in hash table means character is present in 1^{st} string but not in 2^{nd} string, and -1 in hash table means character is present in 2^{nd} string but not in 1^{st} string,.

  • Absolute sum of the hash table is 6 which means a total of 6 characters are different, half of it i.e. 3 is our final answer.


[TABS_R id=1282]
[forminator_quiz id=”1285″]

Space Complexity of this approach would be O(1).

Previous post Form the Largest Number
Next post Minimum Dissatisfaction

Leave a Reply

Your email address will not be published. Required fields are marked *