Minimum Swaps to Make Strings Equal

medium greedy math string

Problem

You are given two strings s1 and s2 of equal length consisting only of the letters 'x' and 'y'. In one operation you may swap any one character of s1 with any one character of s2. Return the minimum number of swaps required to make the two strings equal, or -1 if it is impossible.

Inputs1 = "xxyyxyxyxx", s2 = "xyyxyxxxyx"
Output4
Only mismatched positions matter. Count positions of type xy (s1='x', s2='y') and yx (s1='y', s2='x'). Each pair of same-type mismatches costs 1 swap; one leftover xy plus one leftover yx costs 2 swaps.

def minimum_swap(s1, s2):
    xy = yx = 0
    for a, b in zip(s1, s2):
        if a == 'x' and b == 'y':
            xy += 1
        elif a == 'y' and b == 'x':
            yx += 1
    if (xy + yx) % 2 == 1:
        return -1
    return xy // 2 + yx // 2 + 2 * (xy % 2)
function minimumSwap(s1, s2) {
  let xy = 0, yx = 0;
  for (let i = 0; i < s1.length; i++) {
    if (s1[i] === 'x' && s2[i] === 'y') xy++;
    else if (s1[i] === 'y' && s2[i] === 'x') yx++;
  }
  if ((xy + yx) % 2 === 1) return -1;
  return Math.floor(xy / 2) + Math.floor(yx / 2) + 2 * (xy % 2);
}
class Solution {
    public int minimumSwap(String s1, String s2) {
        int xy = 0, yx = 0;
        for (int i = 0; i < s1.length(); i++) {
            if (s1.charAt(i) == 'x' && s2.charAt(i) == 'y') xy++;
            else if (s1.charAt(i) == 'y' && s2.charAt(i) == 'x') yx++;
        }
        if ((xy + yx) % 2 == 1) return -1;
        return xy / 2 + yx / 2 + 2 * (xy % 2);
    }
}
int minimumSwap(string s1, string s2) {
    int xy = 0, yx = 0;
    for (int i = 0; i < (int)s1.size(); i++) {
        if (s1[i] == 'x' && s2[i] == 'y') xy++;
        else if (s1[i] == 'y' && s2[i] == 'x') yx++;
    }
    if ((xy + yx) % 2 == 1) return -1;
    return xy / 2 + yx / 2 + 2 * (xy % 2);
}
Time: O(n) Space: O(1)