Open In App

Minimum Changes to Make Anagram Without Deletion

Last Updated : 07 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two strings s1 and s2 of equal length and containing lowercase characters, the task is to 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.

Note:- The anagram strings have same set of characters, sequence of characters can be different. 

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 - O(n * log n) time and O(1) space

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). 

Step by step approach:

  1. Sort the characters of both strings.
  2. Initialize two pointers (i and j) to traverse the sorted strings and a counter (count) to track mismatches.
  3. Compare characters at the current positions of the pointers:
    • If they match, move both pointers forward.
    • If the character in s1 is smaller, move the i pointer forward and increment the count.
    • If the character in s2 is smaller, move the j pointer forward and increment the count.
  4. After traversal, count any remaining characters in either string as mismatches.
  5. Return half of the total count as the minimum number of manipulations required.
C++
 // C++ Program to find minimum number 
// of manipulations required to make 
// two strings identical 
#include <bits/stdc++.h>
using namespace std;

int minManipulation(string s1, string s2) {
    
    // Sort the characters of both strings
    sort(s1.begin(), s1.end());
    sort(s2.begin(), s2.end());

    int i = 0, j = 0, count = 0;

    // Compare characters in sorted strings
    while (i < s1.size() && j < s2.size()) {
        if (s1[i] == s2[j]) {
            i++;
            j++;
        }
        else if (s1[i] < s2[j]) {
            i++;
            count++;
        }
        else {
            j++;
            count++;
        }
    }

    // Count the remaining characters in both strings
    while (i < s1.size()) {
        i++;
        count++;
    }

    while (j < s2.size()) {
        j++;
        count++;
    }

    // Return the count divided by 2
    return count / 2;
}

int main() {
    string s1 = "ddcf";
    string s2 = "cedk";
    cout << minManipulation(s1, s2) << endl;
    return 0;
}
Java
// Java Program to find minimum number 
// of manipulations required to make 
// two strings identical 

import java.util.*;

class GfG {

    static int minManipulation(String s1, String s2) {
        
        // Sort the characters of both strings
        char[] arr1 = s1.toCharArray();
        char[] arr2 = s2.toCharArray();
        Arrays.sort(arr1);
        Arrays.sort(arr2);
        
        int i = 0, j = 0, count = 0;

        // Compare characters in sorted strings
        while (i < arr1.length && j < arr2.length) {
            if (arr1[i] == arr2[j]) {
                i++;
                j++;
            }
            else if (arr1[i] < arr2[j]) {
                i++;
                count++;
            }
            else {
                j++;
                count++;
            }
        }

        // Count the remaining characters in both strings
        while (i < arr1.length) {
            i++;
            count++;
        }

        while (j < arr2.length) {
            j++;
            count++;
        }

        // Return the count divided by 2
        return count / 2;
    }

    public static void main(String[] args) {
        String s1 = "ddcf";
        String s2 = "cedk";
        System.out.println(minManipulation(s1, s2));
    }
}
Python
# Python Program to find minimum number 
# of manipulations required to make 
# two strings identical 

# function to calculate minimum numbers of manipulations 
# required to make two strings identical
def minManipulation(s1, s2):
    
    # Sort the characters of both strings
    s1 = sorted(s1)
    s2 = sorted(s2)

    i, j, count = 0, 0, 0

    # Compare characters in sorted strings
    while i < len(s1) and j < len(s2):
        if s1[i] == s2[j]:
            i += 1
            j += 1
        elif s1[i] < s2[j]:
            i += 1
            count += 1
        else:
            j += 1
            count += 1

    # Count the remaining characters in both strings
    while i < len(s1):
        i += 1
        count += 1

    while j < len(s2):
        j += 1
        count += 1

    # Return the count divided by 2
    return count // 2

if __name__ == "__main__":
    s1 = "ddcf"
    s2 = "cedk"
    print(minManipulation(s1, s2))
C#
// C# Program to find minimum number 
// of manipulations required to make 
// two strings identical 

using System;

class GfG {

    static int minManipulation(string s1, string s2) {
        
        // Sort the characters of both strings
        char[] arr1 = s1.ToCharArray();
        char[] arr2 = s2.ToCharArray();
        Array.Sort(arr1);
        Array.Sort(arr2);

        int i = 0, j = 0, count = 0;

        // Compare characters in sorted strings
        while (i < arr1.Length && j < arr2.Length) {
            if (arr1[i] == arr2[j]) {
                i++;
                j++;
            }
            else if (arr1[i] < arr2[j]) {
                i++;
                count++;
            }
            else {
                j++;
                count++;
            }
        }

        // Count the remaining characters in both strings
        while (i < arr1.Length) {
            i++;
            count++;
        }

        while (j < arr2.Length) {
            j++;
            count++;
        }

        // Return the count divided by 2
        return count / 2;
    }

    static void Main() {
        string s1 = "ddcf";
        string s2 = "cedk";
        Console.WriteLine(minManipulation(s1, s2));
    }
}
JavaScript
// JavaScript Program to find minimum number 
// of manipulations required to make 
// two strings identical 

// function to calculate minimum numbers of manipulations 
// required to make two strings identical
function minManipulation(s1, s2) {
    
    // Sort the characters of both strings
    let arr1 = s1.split('').sort();
    let arr2 = s2.split('').sort();

    let i = 0, j = 0, count = 0;

    // Compare characters in sorted strings
    while (i < arr1.length && j < arr2.length) {
        if (arr1[i] === arr2[j]) {
            i++;
            j++;
        }
        else if (arr1[i] < arr2[j]) {
            i++;
            count++;
        }
        else {
            j++;
            count++;
        }
    }

    // Count the remaining characters in both strings
    while (i < arr1.length) {
        i++;
        count++;
    }

    while (j < arr2.length) {
        j++;
        count++;
    }

    // Return the count divided by 2
    return Math.floor(count / 2);
}

let s1 = "ddcf";
let s2 = "cedk";
console.log(minManipulation(s1, s2));

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 the occurrences of each character in both strings. By incrementing the frequency for characters in the first string and decrementing for characters in the second string, we can determine the mismatches in character counts. The total number of mismatches is then divided by 2 because each manipulation fixes two mismatches (one excess in one string and one deficit in the other), ensuring the minimum number of changes required to make the two strings anagrams without deleting any characters.

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.
C++
 // C++ Program to find minimum number 
// of manipulations required to make 
// two strings identical 
#include <bits/stdc++.h>
using namespace std;

int minManipulation(string s1, string s2) {
    
    vector<int> freq(26, 0);
    
    // Increment character frequency 
    // for string s1
    for (char ch: s1) {
        freq[ch-'a']++;
    }
    
    // Decrement character frequency
    // for string s2 
    for (char ch: s2) {
        freq[ch-'a']--;
    }
    
    int count = 0;
    
    // Count the number of mismatches
    for (int i=0; i<26; i++) {
        count += abs(freq[i]);
    }

    // Return the count divided by 2
    return count / 2;
}

int main() {
    string s1 = "ddcf";
    string s2 = "cedk";
    cout << minManipulation(s1, s2) << endl;
    return 0;
}
Java
// Java Program to find minimum number 
// of manipulations required to make 
// two strings identical 

import java.util.*;

class GfG {

    static int minManipulation(String s1, String s2) {
        
        int[] freq = new int[26];
        
        // Increment character frequency 
        // for string s1
        for (char ch : s1.toCharArray()) {
            freq[ch - 'a']++;
        }
        
        // Decrement character frequency
        // for string s2 
        for (char ch : s2.toCharArray()) {
            freq[ch - 'a']--;
        }
        
        int count = 0;
        
        // Count the number of mismatches
        for (int i = 0; i < 26; i++) {
            count += Math.abs(freq[i]);
        }

        // Return the count divided by 2
        return count / 2;
    }

    public static void main(String[] args) {
        String s1 = "ddcf";
        String s2 = "cedk";
        System.out.println(minManipulation(s1, s2));
    }
}
Python
# Python Program to find minimum number 
# of manipulations required to make 
# two strings identical 

# function to calculate minimum numbers of manipulations 
# required to make two strings identical
def minManipulation(s1, s2):
    
    freq = [0] * 26
    
    # Increment character frequency 
    # for string s1
    for ch in s1:
        freq[ord(ch) - ord('a')] += 1
    
    # Decrement character frequency
    # for string s2 
    for ch in s2:
        freq[ord(ch) - ord('a')] -= 1
    
    count = 0
    
    # Count the number of mismatches
    for i in range(26):
        count += abs(freq[i])

    # Return the count divided by 2
    return count // 2

if __name__ == "__main__":
    s1 = "ddcf"
    s2 = "cedk"
    print(minManipulation(s1, s2))
C#
// C# Program to find minimum number 
// of manipulations required to make 
// two strings identical 

using System;

class GfG {

    static int minManipulation(string s1, string s2) {
        
        int[] freq = new int[26];
        
        // Increment character frequency 
        // for string s1
        foreach (char ch in s1) {
            freq[ch - 'a']++;
        }
        
        // Decrement character frequency
        // for string s2 
        foreach (char ch in s2) {
            freq[ch - 'a']--;
        }
        
        int count = 0;
        
        // Count the number of mismatches
        for (int i = 0; i < 26; i++) {
            count += Math.Abs(freq[i]);
        }

        // Return the count divided by 2
        return count / 2;
    }

    static void Main() {
        string s1 = "ddcf";
        string s2 = "cedk";
        Console.WriteLine(minManipulation(s1, s2));
    }
}
JavaScript
// JavaScript Program to find minimum number 
// of manipulations required to make 
// two strings identical 

// function to calculate minimum numbers of manipulations 
// required to make two strings identical
function minManipulation(s1, s2) {
    
    let freq = new Array(26).fill(0);
    
    // Increment character frequency 
    // for string s1
    for (let ch of s1) {
        freq[ch.charCodeAt(0) - 'a'.charCodeAt(0)]++;
    }
    
    // Decrement character frequency
    // for string s2 
    for (let ch of s2) {
        freq[ch.charCodeAt(0) - 'a'.charCodeAt(0)]--;
    }
    
    let count = 0;
    
    // Count the number of mismatches
    for (let i = 0; i < 26; i++) {
        count += Math.abs(freq[i]);
    }

    // Return the count divided by 2
    return Math.floor(count / 2);
}

let s1 = "ddcf";
let s2 = "cedk";
console.log(minManipulation(s1, s2));

Output
2

Article Tags :
Practice Tags :

Similar Reads