Minimum Number of Manipulations required to make two Strings Anagram Without Deletion of Character in JavaScript
Last Updated :
06 Jul, 2024
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)}`);
OutputMinimum 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));
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)}`);
OutputMinimum number of manipulations required are : 3
Similar Reads
Add Minimum Characters at Front to Make String Palindrome in JavaScript The minimum characters to add at the front to make the string palindrome means the smallest count of characters required to prepend to the beginning of a given string. It ensures that the resultant string reads the same forwards and backward. This process creates a palindrome from the original strin
5 min read
Find Minimum Number of Steps to Make Two Strings Anagram II Given two strings S and T, the task is to find the minimum number of steps to make S and T anagrams of each other. In one step, we can append any character to either S or T. Example: Input: S = "gee", T = "eks" Output: 4Explanation: Append 'k' and 's' to string S and append 'g' and 'e' to string T t
3 min read
Javascript Program for Minimum move to end operations to make all strings equal Given n strings that are permutations of each other. We need to make all strings same with an operation that takes front character of any string and moves it to the end.Examples: Input : n = 2 arr[] = {"molzv", "lzvmo"}Output : 2Explanation: In first string, we removefirst element("m") from first st
2 min read
Javascript Program to Minimize characters to be changed to make the left and right rotation of a string same Given a string S of lowercase English alphabets, the task is to find the minimum number of characters to be changed such that the left and right rotation of the string are the same. Examples: Input: S = âabcdâOutput: 2Explanation:String after the left shift: âbcdaâString after the right shift: âdabc
3 min read
Javascript Program To Check Whether Two Strings Are Anagram Of Each Other Write a function to check whether two given strings are anagram of each other or not. An anagram of a string is another string that contains the same characters, only the order of characters can be different. For example, "abcd" and "dabc" are an anagram of each other.Method 1 (Use Sorting):Sort bot
6 min read
How to replace a portion of strings with another value in JavaScript ? In JavaScript, replacing a portion of strings with another value involves using the `replace()` method or regular expressions. This process is essential for text manipulation tasks like formatting, sanitization, or dynamic content generation in web development and data processing applications. We ca
3 min read