Solving Leetcode Interviews in Seconds with AI: Check if One String Swap Can Make Strings Equal
Introduction
In this blog post, we will explore how to solve the LeetCode problem "1790" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
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. Example 1: Input: s1 = "bank", s2 = "kanb" Output: true Explanation: For example, swap the first character with the last character of s2 to make "bank". Example 2: Input: s1 = "attack", s2 = "defend" Output: false Explanation: It is impossible to make them equal with one string swap. Example 3: Input: s1 = "kelb", s2 = "kelb" Output: true Explanation: The two strings are already equal, so no string swap operation is required. Constraints: 1 <= s1.length, s2.length <= 100 s1.length == s2.length s1 and s2 consist of only lowercase English letters.
Explanation
Here's an efficient solution to the string swap problem:
- Identify Differences: Find the indices where the two strings differ.
- Handle Cases: If there are no differences, the strings are equal (return
True). If there are more than two differences, it's impossible to make them equal with one swap (returnFalse). If there are exactly two differences, check if swapping the characters at those indices in either string makes them equal. Optimize: Use early exits (return
Falseimmediately if more than 2 differences are found).Runtime Complexity: O(n), where n is the length of the strings. Storage Complexity: O(1).
Code
def are_almost_equal(s1: str, s2: str) -> bool:
"""
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.
For example:
are_almost_equal("bank", "kanb") == True
are_almost_equal("attack", "defend") == False
are_almost_equal("kelb", "kelb") == True
"""
diff_indices = []
for i in range(len(s1)):
if s1[i] != s2[i]:
diff_indices.append(i)
if not diff_indices:
return True
elif len(diff_indices) == 2:
i, j = diff_indices
return s1[i] == s2[j] and s1[j] == s2[i]
else:
return False