Minimum deletions to make two strings anagrams

Updated

Two Strings are anagrams of each other if both Strings must contain same characters and same number of frequency.

Example :

Input : a="abcd" b="bcdf"
now to make both strings to anagrams we need to remove the 'a'
character from 1st String and 'f' charcater from 2nd String
so we need to make 2 deletion to make anagrams of strings.
after removing 2 charcaters both will have same characters a="bcd"
b="bcd"
Output : 2

Approach

1) store the frequency of each character of both strings in a separate frequency array

2)after storing the frequency of each character of String then store the difference of both frequency array and store the differences in the another variable.

3)and at last return that variable as output.

Implementation :

#include <iostream>
#include <string>
using namespace std;

int makeToAnagram(string a,string b)
{
    int min_del=0;
    int freq[26]={0};
    int freq2[26]={0};

    for(int i=0;i<a.size();i++)
    freq[a[i]-97]++;
    for(int i=0;i<b.size();i++)
    freq2[b[i]-97]++;
    for(int i=0;i< 26;i++)
    {
        int diff=abs(freq[i]-freq2[i]);
        min_del+=diff;
    }
    return min_del;
}
int main() {

    ;
    cout<<makeToAnagram("abcd","bcdf");
    return 0;
}
/*package whatever //do not write package name here */

import java.io.*;

class Main {
    public static int makeToAnagram(String a,String b)
    {
        int min_del=0;
        int[] freq=new int[26];
        int[] freq2=new int[26];
        for(int i=0;i<a.length();i++)
        freq[a.charAt(i)-'a']++;
        for(int i=0;i<b.length();i++)
        freq2[b.charAt(i)-'a']++;
        for(int i=0;i< 26;i++)
        {
            int diff=Math.abs(freq[i]-freq2[i]);
            min_del+=diff;
        }
        return min_del;
    }
    public static void main (String[] args) {
        System.out.println(makeToAnagram("abcd","bcdf"));
    }
}

Output : 2

Comment
RKplus Published 20 Nov 2026 · 2 min read

Related tutorials