Leetcode 1790: Check if One String Swap Can Make Strings Equal

grid47
grid47
Exploring patterns and algorithms
May 12, 2024 5 min read

You are given two strings, s1 and s2, of equal length. A string swap is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices. Return true if it is possible to make both strings equal by performing at most one string swap on exactly one of the strings. Otherwise, return false.
Problem
Approach
Steps
Complexity
Input: You are given two strings, s1 and s2, both of equal length.
Example: Input: s1 = "abc", s2 = "bca"
Constraints:
• 1 <= s1.length, s2.length <= 100
• s1.length == s2.length
• s1 and s2 consist of only lowercase English letters
Output: Return true if it is possible to make both strings equal with at most one swap, otherwise return false.
Example: Output: true
Constraints:
Goal: We need to check if it's possible to make both strings equal by performing at most one swap on one of the strings.
Steps:
• First, check if both strings already match. If they do, return true.
• If they do not match, check if exactly two characters are different between the strings.
• Ensure that swapping the two different characters results in equal strings.
Goal: The solution must handle strings of length up to 100 efficiently.
Steps:
• The length of s1 and s2 must be equal.
• Both strings contain only lowercase letters.
Assumptions:
• The strings are always of equal length.
• Both strings consist of only lowercase English letters.
Input: s1 = "abc", s2 = "bca"
Explanation: By swapping the first and third characters of s2, we can make both strings equal.

Input: s1 = "hello", s2 = "holle"
Explanation: The strings can be made equal by swapping the second and fourth characters of s2.

Input: s1 = "abc", s2 = "xyz"
Explanation: It is impossible to make the strings equal with a single swap, so the result is false.

Link to LeetCode Lab


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