Problem Description
Explanation:
To make the two strings equal, we need to find pairs of characters that are not equal in the two strings and then swap them. We can start by counting the number of 'x' and 'y' characters in each string. If the total count of 'x's or 'y's in both strings is odd, it is impossible to make them equal. Otherwise, we can count the number of mismatched pairs and divide it by 2 to get the minimum number of swaps required.
- Count the number of 'x' and 'y' characters in both strings.
- If the total count of 'x's or 'y's is odd, return -1.
- Count the number of mismatched pairs and return half of it.
Time Complexity: O(n) Space Complexity: O(1)
:
Solutions
class Solution {
public int minimumSwap(String s1, String s2) {
int xCount = 0, yCount = 0, mismatch = 0;
for (int i = 0; i < s1.length(); i++) {
if (s1.charAt(i) == 'x' && s2.charAt(i) == 'y') {
mismatch++;
xCount++;
} else if (s1.charAt(i) == 'y' && s2.charAt(i) == 'x') {
mismatch++;
yCount++;
}
}
if ((xCount + yCount) % 2 != 0) {
return -1;
}
return mismatch / 2 + xCount % 2 + yCount % 2;
}
}
Loading editor...