#1247
Medium Algorithms Minimum swaps to make strings equal
Math String Greedy
65.3% acceptance
Feb 25, 2026
1465
252
You are given two strings s1 and s2 of equal length consisting of letters "x" and "y" only. Your task is to make these two strings equal to each other. You can swap any two characters that belong to different strings, which means: swap s1[i] and s2[j].
Return the minimum number of swaps required to make s1 and s2 equal, or return -1 if it is impossible to do so.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn minimum_swap(s1: String, s2: String) -> i32 {
let mut xy = 0; // positions where s1='x', s2='y'
let mut yx = 0; // positions where s1='y', s2='x'
for (c1, c2) in s1.bytes().zip(s2.bytes()) {
if c1 == b'x' && c2 == b'y' { xy += 1; }
else if c1 == b'y' && c2 == b'x' { yx += 1; }
}
// Check feasibility: xy and yx must have same parity
if (xy + yx) % 2 != 0 { return -1; }
// Each pair of same type: 1 swap
// Remaining (one xy + one yx): 2 swaps
xy / 2 + yx / 2 + 2 * (xy % 2)
}
}