Minimum Swaps to Make Strings Equal — LeetCode 1247 Python Solution
- Problem
- #1247
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
The 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.
Example
- Input
- s1 = "xx", s2 = "yy"
- Output
- 1
- Explanation
- Swap s1[0] and s2[1], s1 = "yx", s2 = "yx".
Python solution
class Solution:
def minimumSwap(self, s1: str, s2: str) -> int:
xy = yx = 0
for a, b in zip(s1, s2):
xy += a < b
yx += a > b
if (xy + yx) % 2:
return -1
return xy // 2 + yx // 2 + xy % 2 + yx % 2Complexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the strings s_1 and s_2 |
| Space | O(1) auxiliary |
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 1247. Minimum Swaps to Make Strings Equal is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.
The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1247. Minimum Swaps to Make Strings Equal?
- LeetCode 1247. Minimum Swaps to Make Strings Equal is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1247. Minimum Swaps to Make Strings Equal?
- The Python solution on this page runs in O(n), where n is the length of the strings s_1 and s_2.
- What is the space complexity of LeetCode 1247. Minimum Swaps to Make Strings Equal?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 1247. Minimum Swaps to Make Strings Equal cover?
- LeetCode 1247. Minimum Swaps to Make Strings Equal is tagged Greedy, Math and String on LeetCode.