Open In App

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

Last Updated : 11 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to learn how we will find the minimum number of manipulations required to make the two strings str1 and str2 an anagram without deleting any character from both strings. Note that two strings are called an anagram of each other only if one string is a permutation of the other.

These are the following approaches:

  • By evaluating Frequencies
  • By Sorting and Comparison

Example:

Input:
str1: 'hello'
str2: 'world'
Output:3
Explanation:
Change 'h' in "hello" to 'w': This requires 1 manipulation.
Change 'e' in "hello" to 'r': This requires 1 manipulation.
Add 'd' from "world" to "hello": This requires 1 manipulation.

Example:

Input:
str1 : 'abcd'
str2 : 'dcba'
Output:
0
Explanation:
Both string are same so we don't require any manipulation.

By evaluating Frequencies

  • Initialize a variable count to 0 which will count the total number of manipulations required.
  • Create an array named freq to store the frequency of each character.
  • Iterate through the characters of the first string str1 and for each character its frequency is incremented in the freq array at the index whose value is calculated by subtracting the ASCII value of lowercase ‘a’ from the ASCII value of the current character.
  • Iterate through the characters of the second string str2 and for each its frequency is decremented in the freq array.
  • After both strings are processed, iterate through the freq array and if the frequency at an index is not zero then there’s a difference in character counts between the two strings. The absolute difference in counts is added to the count variable.
  • At last return count / 2 as each manipulation involves characters from one from each string and the total manipulations required is divided by 2.

Example:

Javascript




// Javascript program for checking
// strings are anagram or not
function count(str1, str2) {
    let count = 0;
    let freq = new Array(26);
    for (let i = 0; i < freq.length; i++) {
        freq[i] = 0;
    }
    for (let i = 0; i < str1.length; i++)
        freq[str1[i].charCodeAt(0) -
            'a'.charCodeAt(0)]++;
    for (let i = 0; i < str2.length; i++) {
        freq[str2[i].charCodeAt(0) -
            'a'.charCodeAt(0)]--;
    }
    for (let i = 0; i < 26; ++i) {
        if (freq[i] !== 0) {
            count += Math.abs(freq[i]);
        }
    }
    return count / 2;
}
 
let str1 = "hello";
let str2 = "world";
// Printing result
console.log(`Minimum number of manipulations
required are : ${count(str1, str2)}`);


Output

Minimum number of manipulations required are : 3


Time Complexity: O(n)

Auxiliary Space: O(1)

By Sorting and Comparison

  • Sort both the strings str1 and str2 in lexicographically increasing order using the sort function and then join them.
  • Initialize a count variable as zero which will count the minimum manipulations required to make both strings anagram.
  • Iterate over both strings str1 and str2 using a while loop and in each iteration compare the characters at each position and check if the characters are equal then do nothing simply increment i and j else increment count by 1.
  • For the remaining characters in both the strings increment count by 1.
  • At last return count/2 because each manipulation affects exactly two characters.

Example:

Javascript




// Javascript program for checking
// strings are anagram or not
function count(str1, str2) {
    str1 = str1.split('').sort().join('');
    str2 = str2.split('').sort().join('');
    let i = 0, j = 0, count = 0;
    while (i < str1.length && j < str2.length) {
        if (str1[i] === str2[j]) {
            i++;
            j++;
        } else if (str1[i] < str2[j]) {
            i++;
            count++;
        } else {
            j++;
            count++;
        }
    }
    while (i < str1.length) {
        i++;
        count++;
    }
    while (j < str2.length) {
        j++;
        count++;
    }
    return Math.floor(count / 2);
}
 
let str1 = "hello";
let str2 = "world";
console.log(count(str1, str2));


Output

3


Time Complexity: O(n log n)

Auxiliary Space: O(1)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads