My approach involves first checking if the two strings, s1 and s2, are equal. If they are, we immediately return true since no swap is needed.
Next, I create a list(array) called diff to store, in a tuple, the characters at a particular index if they are different. Since I can only make one swap, if the length of my diff list is greater than 2 mid way in the loop, then I return false.
- At the end of the loop, If the length of diff is 2 and the first tuple is the reverse of the second tuple in my diff list, then I'll return True, otherwise, I'll return False.
def areAlmostEqual(self, s1: str, s2: str) -> bool:
if s1 == s2:
return True # Strings are already equal
diff = []
for i, (c1, c2) in enumerate(zip(s1, s2)):
if c1 != c2:
diff.append((c1, c2))
if len(diff) > 2:
return False
return len(diff) == 2 and diff[0] == diff[1][::-1]- Time: O(n)
- Space: O(1)
