Open In App

Minimum Number of Manipulations required to make two Strings Anagram Without Deletion of Character

Improve
Improve
Like Article
Like
Save
Share
Report

Given two strings s1 and s2, we need to find the minimum number of manipulations required to make two strings anagram without deleting any character. 

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

If deletion of character is allowed and cost is given, refer to Minimum Cost To Make Two Strings Identical
Question Source: Yatra.com Interview Experience | Set 7 

Examples: 

Input : 
s1 = "aba"
s2 = "baa"
Output : 0
Explanation: Both String contains identical characters
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.

Assumption: Length of both the Strings is considered similar 

Implementation:

C++




// C++ Program to find minimum number
// of manipulations required to make
// two strings identical
#include <bits/stdc++.h>
using namespace std;
 
    // Counts the no of manipulations
    // required
    int countManipulations(string s1, string s2)
    {
         
        int count = 0;
 
        // store the count of character
        int char_count[26];
         
        for (int i = 0; i < 26; i++)
        {
            char_count[i] = 0;
        }
 
        // iterate though the first String
        // and update count
        for (int i = 0; i < s1.length(); i++)
            char_count[s1[i] - 'a']++;
 
        // iterate through the second string
        // update char_count.
        // if character is not found in
        // char_count then increase count
        for (int i = 0; i < s2.length(); i++)
        {
            char_count[s2[i] - 'a']--;      
        }
       
        for(int i = 0; i < 26; ++i)
        {
          if(char_count[i] != 0)
          {
            count+=abs(char_count[i]);
          }
        }
        return count / 2;
    }
 
    // Driver code
    int main()
    {
 
        string s1 = "ddcf";
        string s2 = "cedk";
         
        cout<<countManipulations(s1, s2);
    }
  
// This code is contributed by vt_m.


Java




// Java Program to find minimum number of manipulations
// required to make two strings identical
public class Similar_strings {
 
    // Counts the no of manipulations required
    static int countManipulations(String s1, String s2)
    {
        int count = 0;
 
        // store the count of character
        int char_count[] = new int[26];
 
        // iterate though the first String and update
        // count
        for (int i = 0; i < s1.length(); i++)
            char_count[s1.charAt(i) - 'a']++;       
 
        // iterate through the second string
        // update char_count.
        // if character is not found in char_count
        // then increase count
        for (int i = 0; i < s2.length(); i++)
        {
            char_count[s2.charAt(i) - 'a']--;
        }
       
        for(int i = 0; i < 26; ++i)
        {
          if(char_count[i] != 0)
          {
            count+= Math.abs(char_count[i]);
          }
        }
         
        return count / 2;
    }
 
    // Driver code
    public static void main(String[] args)
    {
 
        String s1 = "ddcf";
        String s2 = "cedk";
        System.out.println(countManipulations(s1, s2));
    }
}


Python3




# Python3 Program to find minimum number
# of manipulations required to make
# two strings identical
 
# Counts the no of manipulations
# required
def countManipulations(s1, s2):
     
    count = 0
 
    # store the count of character
    char_count = [0] * 26
     
    for i in range(26):
        char_count[i] = 0
 
    # iterate though the first String
    # and update count
    for i in range(len( s1)):
        char_count[ord(s1[i]) -
                   ord('a')] += 1
 
    # iterate through the second string
    # update char_count.
    # if character is not found in
    # char_count then increase count
    for i in range(len(s2)):
        char_count[ord(s2[i]) - ord('a')] -= 1
         
    for i in range(26):
        if char_count[i] != 0:
            count += abs(char_count[i])
         
 
    return count / 2
 
# Driver code
if __name__ == "__main__":
 
    s1 = "ddcf"
    s2 = "cedk"
     
    print(countManipulations(s1, s2))
 
# This code is contributed by ita_c


C#




// C# Program to find minimum number
// of manipulations required to make
// two strings identical
using System;
 
public class GFG {
 
    // Counts the no of manipulations
    // required
    static int countManipulations(string s1,
                                  string s2)
    {
        int count = 0;
 
        // store the count of character
        int []char_count = new int[26];
 
        // iterate though the first String
        // and update count
        for (int i = 0; i < s1.Length; i++)
            char_count[s1[i] - 'a']++;
 
        // iterate through the second string
        // update char_count.
        // if character is not found in
        // char_count then increase count
        for (int i = 0; i < s2.Length; i++)
            char_count[s2[i] - 'a']--;
       
        for(int i = 0; i < 26; ++i)
        {
            if(char_count[i] != 0)
            {
              count+= Math.Abs(char_count[i]);
            }
        }
         
        return count / 2;
    }
 
    // Driver code
    public static void Main()
    {
 
        string s1 = "ddcf";
        string s2 = "cedk";
         
        Console.WriteLine(
            countManipulations(s1, s2));
    }
}
 
// This code is contributed by vt_m.


Javascript




<script>
 
// Javascript program to find minimum number
// of manipulations required to make
// two strings identical
     
// Counts the no of manipulations
// required
function countManipulations(s1, s2)
{
    let count = 0;
 
    // Store the count of character
    let char_count = new Array(26);
    for(let i = 0; i < char_count.length; i++)
    {
        char_count[i] = 0;
    }
     
    // Iterate though the first String and
    // update count
    for(let i = 0; i < s1.length; i++)
        char_count[s1[i].charCodeAt(0) -
                     'a'.charCodeAt(0)]++;      
 
    // Iterate through the second string
    // update char_count.
    // If character is not found in char_count
    // then increase count
    for(let i = 0; i < s2.length; i++)
    {
        char_count[s2[i].charCodeAt(0) -
                     'a'.charCodeAt(0)]--;
    }
    
    for(let i = 0; i < 26; ++i)
    {
        if (char_count[i] != 0)
        {
            count += Math.abs(char_count[i]);
        }
    }
    return count / 2;
}
 
// Driver code
let s1 = "ddcf";
let s2 = "cedk";
 
document.write(countManipulations(s1, s2));
 
// This code is contributed by avanitrachhadiya2155
     
</script>


PHP




<?php
// PHP Program to find minimum number
// of manipulations required to make
// two strings identical
 
// Counts the no of manipulations
// required
function countManipulations($s1, $s2)
{
    $count = 0;
 
    // store the count of character
    $char_count = array_fill(0, 26, 0);
 
    // iterate though the first String
    // and update count
    for ($i = 0; $i < strlen($s1); $i++)
        $char_count[ord($s1[$i]) -
                    ord('a')] += 1;
 
    // iterate through the second string
    // update char_count.
    // if character is not found in
    // char_count then increase count
    for ($i = 0; $i < strlen($s2); $i++)
    {
        $char_count[ord($s2[$i]) -
                    ord('a')] -= 1;
         
    }
   
    for ($i = 0; $i < 26; $i++)
    {
      if($char_count[i]!=0)
      {
        $count+=abs($char_count[i]);
      }
    }
    return ($count) / 2;
}
 
// Driver code
$s1 = "ddcf";
$s2 = "cedk";
 
echo countManipulations($s1, $s2);
 
// This code is contributed by Ryuga
?>


Output

2


Time Complexity: O(n), where n is the length of the string. 
Auxiliary Space: O(1).

Approach 2(Sorting and Comparing Characters Approach): 

  • Sort both strings in lexicographic order.
  • Initialize a counter variable to zero.
  • Iterate over both strings simultaneously and compare the characters at each position. If they’re not equal, increment the counter.
  • Return the counter value divided by 2, since each manipulation affects two characters.

C++




// C++ Program to find minimum number
// of manipulations required to make
// two strings identical
#include <iostream>
#include <algorithm>
#include <string>
 
using namespace std;
 
int countManipulations(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 << countManipulations(s1, s2) << endl;
    return 0;
}


Java




// Java Program to find minimum number
// of manipulations required to make
// two strings identical
import java.util.Arrays;
 
public class StringManipulations {
    public static int countManipulations(String s1, String s2) {
        // Convert strings to character arrays and sort them
        char[] s1Array = s1.toCharArray();
        char[] s2Array = s2.toCharArray();
 
        Arrays.sort(s1Array);
        Arrays.sort(s2Array);
 
        int i = 0, j = 0, count = 0;
 
        // Compare characters in sorted arrays
        while (i < s1Array.length && j < s2Array.length) {
            if (s1Array[i] == s2Array[j]) {
                i++;
                j++;
            } else if (s1Array[i] < s2Array[j]) {
                i++;
                count++;
            } else {
                j++;
                count++;
            }
        }
 
        // Count the remaining characters in both arrays
        count += (s1Array.length - i) + (s2Array.length - j);
        return count / 2;
    }
 
    public static void main(String[] args) {
        String s1 = "ddcf";
        String s2 = "cedk";
        System.out.println(countManipulations(s1, s2));
    }
}


Python3




# Python3 Program to find minimum number
# of manipulations required to make
# two strings identical
def count_manipulations(s1, s2):
    # Convert strings to lists and sort them
    s1_list = list(s1)
    s2_list = list(s2)
 
    s1_list.sort()
    s2_list.sort()
 
    i, j, count = 0, 0, 0
 
    # Compare characters in sorted lists
    while i < len(s1_list) and j < len(s2_list):
        if s1_list[i] == s2_list[j]:
            i += 1
            j += 1
        elif s1_list[i] < s2_list[j]:
            i += 1
            count += 1
        else:
            j += 1
            count += 1
 
    # Count the remaining characters in both lists
    count += len(s1_list) - i + len(s2_list) - j
    return count // 2
 
if __name__ == "__main__":
    s1 = "ddcf"
    s2 = "cedk"
    print(count_manipulations(s1, s2))


C#




// C# Program to find minimum number
// of manipulations required to make
// two strings identical
using System;
 
public class StringManipulations
{
    public static int CountManipulations(string s1, string s2)
    {
        // Convert strings to character arrays and sort them
        char[] s1Array = s1.ToCharArray();
        char[] s2Array = s2.ToCharArray();
 
        Array.Sort(s1Array);
        Array.Sort(s2Array);
 
        int i = 0, j = 0, count = 0;
 
        // Compare characters in sorted arrays
        while (i < s1Array.Length && j < s2Array.Length)
        {
            if (s1Array[i] == s2Array[j])
            {
                i++;
                j++;
            }
            else if (s1Array[i] < s2Array[j])
            {
                i++;
                count++;
            }
            else
            {
                j++;
                count++;
            }
        }
 
        // Count the remaining characters in both arrays
        count += (s1Array.Length - i) + (s2Array.Length - j);
        return count / 2;
    }
 
    public static void Main(string[] args)
    {
        string s1 = "ddcf";
        string s2 = "cedk";
        Console.WriteLine(CountManipulations(s1, s2));
    }
}


Javascript




// Javascript Program to find minimum number
// of manipulations required to make
// two strings identical
function countManipulations(s1, s2) {
    // Convert strings to arrays and sort them
    const s1Array = s1.split('').sort();
    const s2Array = s2.split('').sort();
 
    let i = 0, j = 0, count = 0;
 
    // Compare characters in sorted arrays
    while (i < s1Array.length && j < s2Array.length) {
        if (s1Array[i] === s2Array[j]) {
            i++;
            j++;
        } else if (s1Array[i] < s2Array[j]) {
            i++;
            count++;
        } else {
            j++;
            count++;
        }
    }
 
    // Count the remaining characters in both arrays
    count += (s1Array.length - i) + (s2Array.length - j);
    return Math.floor(count / 2);
}
 
const s1 = "ddcf";
const s2 = "cedk";
console.log(countManipulations(s1, s2));


Output

2



Time Complexity:

  • Sorting the strings takes O(n log n) time, where n is the length of the strings.
  • Iterating over the sorted strings takes O(n) time.
  • Therefore, the overall time complexity is O(n log n).

Space Complexity: O(n), where n is the length of the longer string. This is because we need to store the sorted versions of both strings in memory, which can take up to n space.



Last Updated : 01 Sep, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads