Given two strings s1
and s2
of equal length, your task is to determine if there is a way to swap exactly one pair of characters in s1
so that it becomes equal to s2
.
s1
and s2
guaranteed to have the same length?s1
and s2
?To solve this problem, follow these steps:
Comparison: First, ensure s1
and s2
have equal lengths. If they don’t, return False
immediately (given the constraints, though, this should not happen).
Identifying Mismatch: Traverse both strings and identify the indices where they differ.
Conditions for Swap:
s1
and s2
differ, check if swapping these two positions in s1
will equalize the two strings.def areAlmostEqual(s1: str, s2: str) -> bool:
# Step 1: Check if lengths of s1 and s2 are the same
if len(s1) != len(s2):
return False
# Step 2 & 3: Find all positions where the strings differ
mismatches = []
for i in range(len(s1)):
if s1[i] != s2[i]:
mismatches.append(i)
# Step 4: Evaluate mismatch conditions
if len(mismatches) == 0:
# Strings are already equal; one "no-op swap" is trivially possible
return True
elif len(mismatches) == 2:
# Strings differ at exactly two positions
i, j = mismatches
# Check if swapping s1[i] with s1[j] will match s2
if s1[i] == s2[j] and s1[j] == s2[i]:
return True
# In all other cases, return False
return False
By following this strategy, you can effectively determine if the strings s1
and s2
can be made equal with exactly one swap.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?