Skip to main content

Anagram of String

Problem​

Given two strings S1 and S2 in lowercase, the task is to make them anagram. The only allowed operation is to remove a character from any string. Find the minimum number of characters to be deleted to make both the strings anagram. Two strings are called anagram of each other if one of them can be converted into another by rearranging its letters.

Examples:​

Example 1:

Input:
S1 = bcadeh
S2 = hea
Output: 3
Explanation: We need to remove b, c and d from S1.

Example 2:

Input:
S1 = cddgk
S2 = gcd
Output: 2
Explanation: We need to remove d and k from S1.

Your task:​

Complete the function remAnagram() which takes two strings S1, S2 as input parameter, and returns minimum characters needs to be deleted.

  • Expected Time Complexity: O(max(∣S1∣,∣S2∣))O(max(|S1|, |S2|)), where |S| = length of string S
  • Expected Auxiliary Space: O(26)O(26)

Constraints:​

  • 1<=∣S1∣,∣S2∣<=1051 <= |S1|, |S2| <= 10^5

Solution​

Python​

def remAnagram(str1,str2):
CHARS = 26
count1 = [0]*CHARS
count2 = [0]*CHARS
i = 0
while i < len(str1):
count1[ord(str1[i])-ord('a')] += 1
i += 1
i =0
while i < len(str2):
count2[ord(str2[i])-ord('a')] += 1
i += 1
result = 0
for i in range(26):
result += abs(count1[i] - count2[i])
return result

Java​

public int remAnagrams(String s,String s1) {
int count1[] = new int[26];
int count2[] = new int[26];
for (int i = 0; i < s.length() ; i++)
count1[s.charAt(i) -'a']++;
for (int i = 0; i < s1.length() ; i++)
count2[s1.charAt(i) -'a']++;
int result = 0;
for (int i = 0; i < 26; i++)
result += Math.abs(count1[i] - count2[i]);
return result;
}

C++​

int remAnagram(string str1, string str2) {
int count1[26] = {0};
int count2[26] = {0};
for (char c : str1) {
count1[c - 'a']++;
}
for (char c : str2) {
count2[c - 'a']++;
}
int result = 0;
for (int i = 0; i < 26; i++) {
result += abs(count1[i] - count2[i]);
}
return result;
}

C​

int remAnagram(const char* str1, const char* str2) {
int count1[26] = {0};
int count2[26] = {0};
for (int i = 0; str1[i] != '\0'; i++) {
count1[str1[i] - 'a']++;
}
for (int i = 0; str2[i] != '\0'; i++) {
count2[str2[i] - 'a']++;
}
int result = 0;
for (int i = 0; i < 26; i++) {
result += abs(count1[i] - count2[i]);
}
return result;
}
  • Time Complexity: O(max(∣S1∣,∣S2∣))O(max(|S1|, |S2|))
  • Auxiliary Space: O(26)O(26)