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
String Swap Equality Check INPUT s1 = "bank" b 0 a 1 n 2 k 3 s2 = "kanb" k 0 a 1 n 2 b 3 Differences at index 0 and 3 Input Values: s1 = "bank" s2 = "kanb" ALGORITHM STEPS 1 Initialize Store diff indices in list 2 Single Pass Compare Find mismatched positions i=0: b != k [DIFF] idx: 0 i=1: a == a [OK] i=2: n == n [OK] i=3: k != b [DIFF] idx: 3 3 Count Check diff_count == 2? Yes! 4 Swap Validation s1[0]==s2[3] and s1[3]==s2[0]? b==b and k==k? Yes! FINAL RESULT Swap at indices 0 and 3: Before: s1 = "bank" b a n k SWAP After: s1 = "kanb" k a n b s2 = "kanb" s1 == s2 [OK] Output: true Key Insight: For a valid single swap: exactly 2 positions must differ, and characters at these positions must be cross-equal (s1[i]==s2[j] and s1[j]==s2[i]). If 0 differences exist, strings are already equal. TutorialsPoint - Check if One String Swap Can Make Strings Equal | Single Pass Optimal Solution
Asked in
Google 15 Facebook 12 Amazon 8
32.4K Views
Medium Frequency
~15 min Avg. Time
987 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen