Remove minimum number of characters so that two strings become anagram

06 Jul, 2022
Given two strings in lowercase, the task is to make them anagram. The only allowed operation is to remove a character from any string. Find minimum number of characters to be deleted to make both the strings anagram? If two strings contains same data set in any order then strings are called Anagrams. 
Examples :  
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
The idea is to make character count arrays for both the strings and store frequency of each character. Now iterate the count arrays of both strings and difference in frequency of any character abs(count1[str1[i]-‘a’] – count2[str2[i]-‘a’]) in both the strings is the number of character to be removed in either string.  
Implementation:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find minimum number of characters// to be removed to make two strings anagram.#include<bits/stdc++.h>using namespace std;const int CHARS = 26; // function to calculate minimum numbers of characters// to be removed to make two strings anagramint remAnagram(string str1, string str2){    // make hash array for both string and calculate    // frequency of each character    int count1[CHARS] = {0}, count2[CHARS] = {0};     // count frequency of each character in first string    for (int i=0; str1[i]!='\0'; i++)        count1[str1[i]-'a']++;     // count frequency of each character in second string    for (int i=0; str2[i]!='\0'; i++)        count2[str2[i]-'a']++;     // traverse count arrays to find number of characters    // to be removed    int result = 0;    for (int i=0; i<26; i++)        result += abs(count1[i] - count2[i]);    return result;} // Driver program to run the caseint main(){    string str1 = "bcadeh", str2 = "hea";    cout << remAnagram(str1, str2);    return 0;}
// Java program to find minimum number of// characters to be removed to make two// strings anagram.import java.util.*; class GFG {     // function to calculate minimum numbers    // of characters to be removed to make    // two strings anagram    static int remAnagram(String str1, String str2)    {        // make hash array for both string        // and calculate frequency of each        // character        int count1[] = new int[26];        int count2[] = new int[26];         // count frequency of each character        // in first string        for (int i = 0; i < str1.length() ; i++)            count1[str1.charAt(i) -'a']++;             // count frequency of each character        // in second string        for (int i = 0; i < str2.length() ; i++)            count2[str2.charAt(i) -'a']++;         // traverse count arrays to find        // number of characters to be removed        int result = 0;        for (int i = 0; i < 26; i++)            result += Math.abs(count1[i] -                               count2[i]);        return result;    }     // Driver program to run the case    public static void main(String[] args)    {        String str1 = "bcadeh", str2 = "hea";        System.out.println(remAnagram(str1, str2));    }}// This code is contributed by Prerna Saini
# Python 3 program to find minimum# number of characters# to be removed to make two# strings anagram. CHARS = 26 # function to calculate minimum# numbers of characters# to be removed to make two# strings anagramdef remAnagram(str1, str2):     # make hash array for both string    # and calculate    # frequency of each character    count1 = [0]*CHARS    count2 = [0]*CHARS     # count frequency of each character    # in first string    i = 0    while i < len(str1):        count1[ord(str1[i])-ord('a')] += 1        i += 1     # count frequency of each character    # in second string    i =0    while i < len(str2):        count2[ord(str2[i])-ord('a')] += 1        i += 1     # traverse count arrays to find    # number of characters    # to be removed    result = 0    for i in range(26):        result += abs(count1[i] - count2[i])    return result # Driver program to run the caseif __name__ == "__main__":    str1 = "bcadeh"    str2 = "hea"    print(remAnagram(str1, str2))     # This code is contributed by# ChitraNayal
// C# program to find minimum// number of characters to be// removed to make two strings// anagram.using System; class GFG{     // function to calculate    // minimum numbers of    // characters to be removed    // to make two strings anagram    static int remAnagram(string str1,                          string str2)    {        // make hash array for both        // string and calculate frequency        // of each character        int []count1 = new int[26];        int []count2 = new int[26];         // count frequency of each        // character in first string        for (int i = 0; i < str1.Length ; i++)            count1[str1[i] -'a']++;             // count frequency of each         // character in second string        for (int i = 0; i < str2.Length ; i++)            count2[str2[i] -'a']++;         // traverse count arrays to        // find number of characters        // to be removed        int result = 0;        for (int i = 0; i < 26; i++)            result += Math.Abs(count1[i] -                               count2[i]);        return result;    }     // Driver Code    public static void Main()    {        string str1 = "bcadeh",               str2 = "hea";        Console.Write(remAnagram(str1, str2));    }} // This code is contributed// by nitin mittal.
<?php// PHP program to find minimum number of// characters to be removed to make two// strings anagram. // function to calculate minimum numbers// of characters to be removed to make// two strings anagramfunction remAnagram($str1, $str2){    // make hash array for both string    // and calculate frequency of each    // character    $count1 = array(26);    $count2 = array(26);     // count frequency of each character    // in first string    for ($i = 0; $i < strlen($str1) ; $i++)        $count1[$str1[$i] - 'a']++;     // count frequency of each character    // in second string    for ($i = 0; $i < strlen($str2) ; $i++)        $count2[$str2[$i] -'a']++;     // traverse count arrays to find    // number of characters to be removed    $result = 0;    for ($i = 0; $i < 26; $i++)        $result += abs($count1[$i] -                       $count2[$i]);    return $result;} // Driver Code{    $str1 = "bcadeh"; $str2 = "hea";    echo(remAnagram($str1, $str2));} // This code is contributed by Code_Mech
<script>// javascript program to find minimum number of// characters to be removed to make two// strings anagram. // function to calculate minimum numbers// of characters to be removed to make// two strings anagramfunction remAnagram(str1, str2){    // make hash array for both string    // and calculate frequency of each    // character    var count1 = Array.from({length: 26}, (_, i) => 0);    var count2 = Array.from({length: 26}, (_, i) => 0);     // count frequency of each character    // in first string    for (i = 0; i < str1.length ; i++)        count1[str1.charAt(i).charCodeAt(0) -'a'.charCodeAt(0)]++;     // count frequency of each character    // in second string    for (i = 0; i < str2.length ; i++)        count2[str2.charAt(i).charCodeAt(0) -'a'.charCodeAt(0)]++;     // traverse count arrays to find    // number of characters to be removed    var result = 0;    for (i = 0; i < 26; i++)        result += Math.abs(count1[i] -                           count2[i]);    return result;} // Driver program to run the casevar str1 = "bcadeh", str2 = "hea";document.write(remAnagram(str1, str2)); // This code is contributed by Amit Katiyar</script>
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
3
Time Complexity : O(n) Auxiliary space : O(ALPHABET-SIZE)
The above solution can be optimized to work with single count array.  
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation to count number of deletions// required from two strings to create an anagram#include <bits/stdc++.h>using namespace std;const int CHARS = 26; int countDeletions(string str1, string str2){    int arr[CHARS] = {0};    for (int i = 0; i < str1.length(); i++)        arr[str1[i] - 'a']++;         for (int i = 0; i < str2.length(); i++)        arr[str2[i] - 'a']--;         long long int ans = 0;    for(int i = 0; i < CHARS; i++)        ans +=abs(arr[i]);    return ans;} int main() {    string str1 = "bcadeh", str2 = "hea";    cout << countDeletions(str1, str2);    return 0;}
// Java implementation to count number of deletions// required from two strings to create an anagram class GFG {     final static int CHARS = 26;     static int countDeletions(String str1, String str2) {        int arr[] = new int[CHARS];        for (int i = 0; i < str1.length(); i++) {            arr[str1.charAt(i) - 'a']++;        }         for (int i = 0; i < str2.length(); i++) {            arr[str2.charAt(i) - 'a']--;        }         int ans = 0;        for (int i = 0; i < CHARS; i++) {            ans += Math.abs(arr[i]);        }        return ans;    }     static public void main(String[] args) {        String str1 = "bcadeh", str2 = "hea";        System.out.println(countDeletions(str1, str2));    }} // This code is contributed by 29AjayKumar
# Python3 program to find minimum# number of characters to be# removed to make two strings# anagram. # function to calculate minimum# numbers of characters to be# removed to make two strings anagramdef makeAnagram(a, b):    buffer = [0] * 26    for char in a:        buffer[ord(char) - ord('a')] += 1    for char in b:        buffer[ord(char) - ord('a')] -= 1    return sum(map(abs, buffer)) # Driver Codeif __name__ == "__main__" :     str1 = "bcadeh"    str2 = "hea"    print(makeAnagram(str1, str2))     # This code is contributed# by Raghib Ahsan
     // C# implementation to count number of deletions// required from two strings to create an anagramusing System;public class GFG {      readonly static int CHARS = 26;      static int countDeletions(String str1, String str2) {        int []arr = new int[CHARS];        for (int i = 0; i < str1.Length; i++) {            arr[str1[i]- 'a']++;        }          for (int i = 0; i < str2.Length; i++) {            arr[str2[i] - 'a']--;        }          int ans = 0;        for (int i = 0; i < CHARS; i++) {            ans += Math.Abs(arr[i]);        }        return ans;    }      static public void Main() {        String str1 = "bcadeh", str2 = "hea";        Console.WriteLine(countDeletions(str1, str2));    }}  //This code is contributed by PrinciRaj1992
<?php// PHP implementation to count number of deletions// required from two strings to create an anagram function countDeletions($str1, $str2){    $CHARS = 26;    $arr = array();    for ($i = 0; $i < strlen($str1); $i++)    {        $arr[ord($str1[$i]) - ord('a')]++;    }     for ($i = 0; $i < strlen($str2); $i++)    {        $arr[ord($str2[$i]) - ord('a')]--;    }     $ans = 0;    for ($i = 0; $i < $CHARS; $i++)    {        $ans += abs($arr[$i]);    }    return $ans;} // Driver Code$str1 = "bcadeh"; $str2 = "hea";echo(countDeletions($str1, $str2)); // This code is contributed by Code_Mech?>
<script> // Javascript implementation to count// number of deletions required from// two strings to create an anagramCHARS = 26; function countDeletions(str1, str2){    var arr = Array.from({length: CHARS}, (_, i) => 0);         for(i = 0; i < str1.length; i++)    {        arr[str1.charAt(i).charCodeAt(0) -                       'a'.charCodeAt(0)]++;    }     for(i = 0; i < str2.length; i++)    {        arr[str2.charAt(i).charCodeAt(0) -                       'a'.charCodeAt(0)]--;    }     var ans = 0;    for(i = 0; i < CHARS; i++)    {        ans += Math.abs(arr[i]);    }    return ans;} // Driver codestr1 = "bcadeh", str2 = "hea"; document.write(countDeletions(str1, str2)); // This code is contributed by Rajput-Ji </script>
3
Thanks to vishal9619 for suggesting this optimized solution.
This article is contributed by Shashank Mishra ( Gullu ). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. 
nitin mittal
Raghib Ahsan
ukasp
29AjayKumar
princiraj1992
Code_Mech
shubham_singh
Rajput-Ji
amit143katiyar
hardikkoriintern
Amazon
anagram
Strings
Amazon
Strings
anagram
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.