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 to Make Strings Equal INPUT s1 = "xx" x x [0] [1] s2 = "yy" y y [0] [1] Mismatches Found: Position 0: x vs y (xy pair) Position 1: x vs y (xy pair) xy pairs: 2, yx pairs: 0 ALGORITHM STEPS 1 Count Mismatches Count xy pairs and yx pairs 2 Check Feasibility (xy + yx) must be even 3 Same Type Pairs 2 same pairs = 1 swap 4 Mixed Type Pairs 1 xy + 1 yx = 2 swaps Swap Visualization: Before: x x y y swap After: x y s1 s2 FINAL RESULT Calculation: xy pairs = 2 yx pairs = 0 Swaps = xy/2 + yx/2 Swaps = 2/2 + 0/2 = 1 After 1 Swap: s1 = "xy" x y s2 = "xy" x y Output: 1 Minimum Swaps Key Insight: Two same-type mismatches (xx/yy or yy/xx) can be fixed with 1 swap. Two different-type mismatches (xy and yx) require 2 swaps. Formula: swaps = (xy/2) + (yx/2) + 2*(xy%2). If total mismatches is odd, return -1 (impossible). Time: O(n), Space: O(1). TutorialsPoint - Minimum Swaps to Make Strings Equal | Optimal Solution
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