VOOZH about

URL: https://www.geeksforgeeks.org/dsa/remove-minimum-number-characters-two-strings-become-anagram/

⇱ Remove minimum characters so that two strings become anagram - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Remove minimum characters so that two strings become anagram

Last Updated : 3 May, 2026

Given two strings in lowercase, the task is to make them anagrams. 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 anagrams of each other if one of them can be converted into another by rearranging its letters.

Examples :

Input : s1 = "bcadeh", s2 = "hea"
Output: 3
Explanation: We need to remove b, c and d from s1.

Input : s1 = "cddgk", s2 = "gcda"
Output: 3
Explanation: Remove one occurrence of d and k from s1 and one occurrence of a from s2.

Input : s1 = "bca", s2 = "acb"
Output: 0
Explanation: Strings are already anagrams.

Using 2 Frequency Arrays - O(n + m) Time and O(1) Space

The idea is to use frequency counting to determine the number of characters that need to be removed from both strings to make them anagrams. By comparing the frequency of each character in both strings, we can calculate the total number of deletions required to balance the frequencies.

Step by step approach:

  1. Initialize two frequency arrays of size 26 (for each lowercase letter).
  2. Traverse the first string and increment the count of each character in the first frequency array.
  3. Traverse the second string and increment the count of each character in the second frequency array.
  4. Traverse both frequency arrays and calculate the sum of absolute differences in counts for each character.
  5. Return the total count of deletions as the result.

Output
3

Using One Frequency Array - O(n + m) Time and O(1) Space

The idea is to use one count array, increment frequencies for first string and decrease for second string.

  • Create a single frequency array.
  • Increment frequency for each character in the count array.
  • Decrement frequency of each character in the same array.
  • Return sum of absolute values in the frequency array.

Output
3

Using Hash Map - O(n + m) Time and O(1) Space

The idea is similar to the first two approaches, but instead of using an array, hash map is used. This approach is useful when the strings can contain different types of characters (lowercase, uppercase, special symbols).


Output
3
Comment
Article Tags: