Minimum Swaps to Make Strings Equal - Problem

You are given two strings s1 and s2 of equal length, where each string contains only the characters 'x' and 'y'. Your goal is to make both strings identical by performing the minimum number of character swaps.

The twist? You can only swap characters that belong to different strings. That is, you can swap s1[i] with s2[j] for any valid indices i and j.

Your task: Return the minimum number of swaps required to make s1 and s2 equal, or return -1 if it's impossible.

Example: If s1 = "xx" and s2 = "yy", you can swap s1[0] with s2[0] to get s1 = "yx" and s2 = "xy", then swap s1[1] with s2[0] to get both strings as "xx" or "yy".

Input & Output

example_1.py โ€” Basic Case
$ Input: s1 = "xx", s2 = "yy"
โ€บ Output: 1
๐Ÿ’ก Note: We can swap s1[0] with s2[1] to get s1="yx", s2="yx". Now both strings are equal with 1 swap.
example_2.py โ€” Multiple Swaps
$ Input: s1 = "xy", s2 = "yx"
โ€บ Output: 2
๐Ÿ’ก Note: We can swap s1[0] with s2[0] to get s1="yy", s2="xx", then swap s1[1] with s2[1] to get s1="yx", s2="xy". We need 2 swaps total, but we can also make both "xx" or "yy" in 2 swaps.
example_3.py โ€” Impossible Case
$ Input: s1 = "xx", s2 = "xy"
โ€บ Output: -1
๐Ÿ’ก Note: There are 3 x's and 1 y in total. Since we can only swap characters between strings, we cannot balance them equally. It's impossible to make both strings identical.

Visualization

Tap to expand
String Balancing VisualizationInitial State:s1:xyxxs2:yxyyPattern Analysis:Mismatch CountPosition 0: xโ†’y (xy pattern)Position 1: yโ†’x (yx pattern)Position 2: xโ†’y (xy pattern)Position 3: xโ†’y (xy pattern)Swap Strategy:Optimal Swapping Formulaxy patterns: 3, yx patterns: 1Min swaps = (3+1)/2 + (1+1)/2 = 2 + 1 = 3 swapsResult: 3 swaps needed
Understanding the Visualization
1
Identify Mismatches
Find positions where the two strings differ
2
Categorize Patterns
Group mismatches into xy and yx types
3
Optimal Pairing
Pair mismatches optimally to minimize total swaps
4
Calculate Result
Apply mathematical formula for minimum swaps
Key Takeaway
๐ŸŽฏ Key Insight: By categorizing mismatches into xy and yx patterns, we can calculate the minimum swaps mathematically without simulation

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Single pass through both strings to count mismatch patterns

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only using constant extra space for counters

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค s1.length, s2.length โ‰ค 1000
  • s1.length == s2.length
  • s1[i] and s2[i] are either 'x' or 'y'
  • Both strings contain only characters 'x' and 'y'
Asked in
Google 35 Amazon 28 Meta 22 Microsoft 18
23.4K Views
Medium Frequency
~15 min Avg. Time
892 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