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)
Minimum Number of Manipulations required to make two Strings Anagram Without Deletion of Character in JavaScript
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.