Check if One String Swap Can Make Strings Equal

You are given two strings `s1` and `s2` of equal length. A string swap picks two indices in one string (they may be the same index) and swaps the characters at those indices. Return `true` if you can make the two strings equal by performing **at most one** string swap on **exactly one** of them. Otherwise return `false`.

30:00

Check if One String Swap Can Make Strings Equal
easy
Free written solution
Topics
Companies

You are given two strings s1 and s2 of equal length. A string swap picks two indices in one string (they may be the same index) and swaps the characters at those indices.

Return true if you can make the two strings equal by performing at most one string swap on exactly one of them. Otherwise return false.

Example 1:
Input: {"s1":"bank","s2":"kanb"}
Output: true
Constraints:
  • 1≤s1.length,s2.length≤1001 \leq s1.\text{length}, s2.\text{length} \leq 100

  • s1.length == s2.length

  • s1 and s2 consist of only lowercase English letters.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"s1":"bank","s2":"kanb"}

Line up s1 over s2 column by column. One swap can fix at most two columns, so record each mismatched index in diff.

s1 over s2, one column per index

s1

s2

b
k

0

a
a

1

n
n

2

k
b

3

diff (mismatched indices)

a
b

one swap fixes at most 2 slots

Variables
VariableValue
n4
diff[]
DepthFunction Call
Stack empty
0/9