I first check if the two strings are already equal. If they are, I return True
immediately since no swaps are needed. Otherwise, I identify the positions where the characters in s1
and s2
differ. I do this by iterating through both strings and collecting the indices where their characters do not match.
If the number of differences is more than two, I return False
. If there is exactly one difference, I also return False
since swapping requires at least two differing positions. However, if there are exactly two mismatches, I check whether swapping the mismatched characters in one of the strings would make the strings equal. If so, I return True
; otherwise, I return False
.
class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
diff_indices = []
for i in range(len(s1)):
if s1[i] != s2[i]:
diff_indices.append(i)
if not diff_indices:
return True
if len(diff_indices) == 2:
i, j = diff_indices
return s1[i] == s2[j] and s1[j] == s2[i]
return False
- Time: O(n)
- Space: O(1)
