Open In App

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

Last Updated : 06 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
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)

Using a Hash Map

In this approach, we will use a hash map (or dictionary in Python) to count the frequency of characters in both strings and calculate the minimum manipulations required to make them anagrams.

Approach:

  • Initialize a hash map (or dictionary) to store the frequency of characters from both strings.
  • Iterate through the first string and increment the count for each character in the hash map.
  • Iterate through the second string and decrement the count for each character in the hash map.
  • Sum up the absolute values of the differences in counts for all characters in the hash map. This sum represents the total number of character manipulations needed.
  • Return half of this sum because each manipulation involves characters from both strings.

Example:

JavaScript
// Javascript program for checking 
// strings are anagram or not using Hash Map
function count(str1, str2) {
    let freqMap = new Map();

    // Increment the frequency for each character in str1
    for (let char of str1) {
        if (freqMap.has(char)) {
            freqMap.set(char, freqMap.get(char) + 1);
        } else {
            freqMap.set(char, 1);
        }
    }

    // Decrement the frequency for each character in str2
    for (let char of str2) {
        if (freqMap.has(char)) {
            freqMap.set(char, freqMap.get(char) - 1);
        } else {
            freqMap.set(char, -1);
        }
    }

    // Calculate the total manipulations required
    let totalManipulations = 0;
    for (let value of freqMap.values()) {
        totalManipulations += Math.abs(value);
    }

    return totalManipulations / 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




Next Article

Similar Reads