The Wayback Machine - https://web.archive.org/web/20211025194239/https://www.geeksforgeeks.org/remove-minimum-number-characters-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 :
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
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.
C++
// C++ program to find minimum number of characters
// to be removed to make two strings anagram.
#include<bits/stdc++.h>
usingnamespacestd;
constintCHARS = 26;
// function to calculate minimum numbers of characters
// to be removed to make two strings anagram
intremAnagram(string str1, string str2)
{
// make hash array for both string and calculate
// frequency of each character
intcount1[CHARS] = {0}, count2[CHARS] = {0};
// count frequency of each character in first string
for(inti=0; str1[i]!='\0'; i++)
count1[str1[i]-'a']++;
// count frequency of each character in second string
for(inti=0; str2[i]!='\0'; i++)
count2[str2[i]-'a']++;
// traverse count arrays to find number of characters
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 contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy