VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimum-number-of-manipulations-required-to-make-two-strings-anagram-without-deletion-of-character/

⇱ Minimum Changes to Make Anagram Without Deletion - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum Changes to Make Anagram Without Deletion

Last Updated : 16 Jun, 2026

Given two strings s1 and s2 of equal length and containing lowercase characters, find the minimum number of manipulations required to make two strings anagram without deleting any character. In each modification, we can change any one character from either string.

Examples:

Input : s1 = "aba", s2 = "baa"
Output : 0
Explanation: Strings are already anagrams.

Input : s1 = "ddcf", s2 = "cedk"
Output : 2
Explanation : Here, we need to change two characters in either of the strings to make them identical. We
can change 'd' and 'f' in s1 or 'e' and 'k' in s2.

[Naive Approach] Using Sorting

The idea is to sort both strings and then compare them character by character to count the number of mismatches. Since each mismatch represents a manipulation needed to make the strings anagrams, the total count of mismatches is divided by 2 because each manipulation fixes two mismatches (one in each string). 


Output
2

Time Complexity: O(n * log n) to sort the input strings.
Auxiliary Space: O(n) in java and c# as input strings cannot be sorted. O(1) in other languages.

[Expected Approach] Using Frequency Array - O(n) Time and O(1) space

The idea is to use a frequency array to count characters in both strings by increasing the count for characters of the first string and decreasing for the second string. The total absolute difference in frequencies represents the number of mismatched characters. Since one change corrects two mismatches (one extra and one missing character), dividing the total by 2 gives the minimum number of changes required to make the strings anagrams.

Step by step approach:

  1. Initialize a frequency array of size 26 (for each lowercase letter) with zeros.
  2. Traverse the first string (s1) and increment the frequency of each character in the array.
  3. Traverse the second string (s2) and decrement the frequency of each character in the array.
  4. Calculate the total number of mismatches by summing the absolute values of the frequencies in the array.
  5. Return half of the total mismatches as the minimum number of manipulations required.

Output
2
Comment
Article Tags:
Article Tags: