[11 Feb 2020] Remove minimum number of characters so that two strings become anagram



Remove minimum number of characters so that two strings become anagram


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

// 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;

Output :
3

// 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

Output :
3

def 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 Code
if __name__ == "__main__"
  
    str1 = "bcadeh"
    str2 = "hea"
    print(makeAnagram(str1, str2))
      
# This code is contributed 
# by Raghib Ahsan

Output :
3
































Comments

Popular posts from this blog

[16 Feb 2020] Given an array where every element occurs three times, except one element which occurs only once.

Which data structure is used in redo-undo feature?

Important Program Collection