Remove minimum number of characters so that two strings become anagram - GeeksforGeeks
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.
Read full article from Remove minimum number of characters so that two strings become anagram - GeeksforGeeks
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.
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.
int
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 charcter in first string
for
(
int
i=0; str1[i]!=
'\0'
; i++)
count1[str1[i]-
'a'
]++;
// count frequency of each charcter in second string
for
(
int
i=0; str2[i]!=
'\0'
; i++)
count2[str2[i]-
'a'
]++;
// traverse count arrays to find number of charcters
// to be removed
int
result = 0;
for
(
int
i=0; i<26; i++)
result +=
abs
(count1[i] - count2[i]);
return
result;
}