Leetcode 1247: Minimum Swaps to Make Strings Equal

grid47
grid47
Exploring patterns and algorithms
Jul 5, 2024 5 min read

You are given two strings s1 and s2 of equal length consisting only of ‘x’ and ‘y’. Your task is to make these two strings equal by swapping characters between the two strings. Return the minimum number of swaps required to make s1 and s2 equal, or return -1 if it is impossible.
Problem
Approach
Steps
Complexity
Input: You are given two strings s1 and s2 of equal length, containing only 'x' and 'y'.
Example: s1 = "yy", s2 = "xx"
Constraints:
• 1 <= s1.length, s2.length <= 1000
• s1.length == s2.length
• s1, s2 only contain 'x' and 'y'.
Output: Return the minimum number of swaps required to make s1 and s2 equal, or -1 if it is impossible.
Example: 1
Constraints:
• Return -1 if it is impossible to make the strings equal.
Goal: Determine the minimum number of swaps needed to make the two strings equal.
Steps:
• Count the number of occurrences where 'x' in s1 corresponds to 'y' in s2, and vice versa.
• Check if the total number of mismatches can be resolved by swapping, ensuring the number of mismatches of 'x' and 'y' are even.
• Return the number of swaps needed or -1 if it is impossible.
Goal: The strings consist only of 'x' and 'y', and their lengths are equal.
Steps:
• 1 <= s1.length, s2.length <= 1000
• s1.length == s2.length
• Both strings only contain 'x' and 'y'.
Assumptions:
• Both strings are non-empty and have equal lengths.
Input: s1 = "yy", s2 = "xx"
Explanation: One swap is enough to make the strings equal: Swap s1[0] and s2[1].

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus