Check if One String Swap Can Make Strings Equal - Problem
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.
Input & Output
Example 1 — Valid Single Swap
$
Input:
s1 = "bank", s2 = "kanb"
›
Output:
true
💡 Note:
Swap s1[0] and s1[3]: "bank" → "kanb". Characters differ at positions 0 and 3, and swapping them makes strings equal.
Example 2 — Already Equal
$
Input:
s1 = "ab", s2 = "ab"
›
Output:
true
💡 Note:
Strings are already equal, no swap needed. Zero differences allow for equality.
Example 3 — Too Many Differences
$
Input:
s1 = "aa", s2 = "bc"
›
Output:
false
💡 Note:
Characters differ at both positions, but swapping any two characters in s1 cannot produce "bc" since frequencies don't match.
Constraints
- 1 ≤ s1.length, s2.length ≤ 100
- s1.length == s2.length
- s1 and s2 consist of only lowercase English letters
Visualization
Tap to expand
Understanding the Visualization
1
Input
Two strings of equal length: s1 = "bank", s2 = "kanb"
2
Process
Find differing positions and validate swap possibility
3
Output
Return true if at most one swap can make strings equal
Key Takeaway
🎯 Key Insight: Strings can be made equal with one swap only when they differ in exactly 0 or 2 positions, and the differing characters can be cross-swapped
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code