#1247
Minimum Swaps to Make Strings Equal
MediumMathStringGreedyHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal approach focuses on counting the mismatched characters and calculating the minimum swaps needed based on the counts of 'x' and 'y'. This is more efficient because it avoids unnecessary checks and directly computes the result.
⚙️
Algorithm
3 steps- 1Step 1: Count the number of 'x's and 'y’s in both strings.
- 2Step 2: Check if the total counts of 'x' and 'y' are even; if not, return -1 (impossible to balance).
- 3Step 3: Calculate the number of swaps needed using the formula: swaps = (count_x_in_s1 - count_x_in_s2) / 2.
solution.py12 lines
1# Full working Python code
2
3def min_swaps(s1, s2):
4 count_x1 = s1.count('x')
5 count_y1 = s1.count('y')
6 count_x2 = s2.count('x')
7 count_y2 = s2.count('y')
8 if (count_x1 + count_x2) % 2 != 0:
9 return -1
10 swaps = abs(count_x1 - count_x2) // 2
11 return swaps
12ℹ
Complexity note: This complexity is linear because we only traverse each string once to count the characters.
- 1Both strings must have the same number of 'x's and 'y’s for it to be possible to make them equal.
- 2The number of swaps needed can be derived from the difference in counts of 'x's and 'y’s.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.