Minimum Swaps to Make Strings Equal - Problem

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.

Input & Output

Example 1 — Equal xy mismatches
$ Input: s1 = "xx", s2 = "yy"
Output: 1
💡 Note: Two xy mismatches at positions 0 and 1. Swap s1[0] with s2[1]: s1="yx", s2="yx". One swap makes them equal.
Example 2 — Mixed mismatch types
$ Input: s1 = "xy", s2 = "yx"
Output: 2
💡 Note: One xy mismatch at pos 0, one yx mismatch at pos 1. Need 2 swaps: swap s1[0] with s1[1] via s2[0], then fix remaining.
Example 3 — Impossible case
$ Input: s1 = "xx", s2 = "xy"
Output: -1
💡 Note: Only 1 mismatch (odd number). Cannot make strings equal since total x's and y's must be even.

Constraints

  • 1 ≤ s1.length, s2.length ≤ 1000
  • s1.length == s2.length
  • s1[i] and s2[i] are either 'x' or 'y'

Visualization

Tap to expand
Minimum Swaps: Pattern Recognitionxxyys1:yyxxs2:xy: 2 countyx: 0 countFormula(xy + 1) / 2 + (yx + 1) / 2= (2 + 1) / 2 + (0 + 1) / 2= 1 + 0 = 1 swapResult: 1 minimum swap needed
Understanding the Visualization
1
Input Analysis
Two strings with only 'x' and 'y' characters
2
Count Patterns
Count xy and yx mismatches
3
Apply Formula
Calculate minimum swaps using mathematical pattern
Key Takeaway
🎯 Key Insight: Two mismatches of the same type need only 1 swap, mixed types need 2 swaps each
Asked in
Google 15 Facebook 12 Amazon 8
23.4K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen