![]() |
VOOZH | about |
Given two strings s1 and s2 of equal length and containing lowercase characters, find the minimum number of manipulations required to make two strings anagram without deleting any character. In each modification, we can change any one character from either string.
Examples:
Input : s1 = "aba", s2 = "baa"
Output : 0
Explanation: Strings are already anagrams.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.
Table of Content
The idea is to sort both strings and then compare them character by character to count the number of mismatches. Since each mismatch represents a manipulation needed to make the strings anagrams, the total count of mismatches is divided by 2 because each manipulation fixes two mismatches (one in each string).
2
Time Complexity: O(n * log n) to sort the input strings.
Auxiliary Space: O(n) in java and c# as input strings cannot be sorted. O(1) in other languages.
The idea is to use a frequency array to count characters in both strings by increasing the count for characters of the first string and decreasing for the second string. The total absolute difference in frequencies represents the number of mismatched characters. Since one change corrects two mismatches (one extra and one missing character), dividing the total by 2 gives the minimum number of changes required to make the strings anagrams.
2