Check if One String Swap Can Make Strings Equal (LeetCode 1790): Solution and Explanation
Two strings of equal length are given. Decide whether swapping two characters inside one of them, at most once, makes the strings equal.
Intuition
A swap only ever changes two positions of a string. Every position where s1 and s2 already agree must stay as it is, so the swap has to land exactly on the positions where they disagree.
That gives three cases. No mismatches: the strings are already equal and zero swaps is allowed. One mismatch: a swap would have to move a letter into that slot from a matching slot, which breaks that slot, so it fails. Three or more: two positions cannot fix three.
With exactly two mismatches at a and b, the only useful swap exchanges those two letters. It works when the letters cross: s1[a] == s2[b] and s1[b] == s2[a].
Approach: Collect mismatched indices
- Walk both strings together. Whenever
s1[i] != s2[i], appenditodiff. - If
diffalready holds two indices when a new mismatch appears, return false right away. - After the loop, return true if
diffis empty. - Return false if
diffholds exactly one index. - Otherwise let
a, b = diffand returns1[a] == s2[b] and s1[b] == s2[a].
Step-by-step example
s1 = "bank", s2 = "kanb"
- Column 0: 'b' vs 'k' differ, so diff = [0].
- Column 1: 'a' vs 'a' match.
- Column 2: 'n' vs 'n' match.
- Column 3: 'k' vs 'b' differ, so diff = [0, 3].
- Exactly two mismatches: a = 0, b = 3.
- s1[0] = 'b' equals s2[3] = 'b', and s1[3] = 'k' equals s2[0] = 'k'. Swapping s2[0] and s2[3] gives "bank", so the answer is true.
Code: Python, Java, C++
1class Solution:
2 def areAlmostEqual(self, s1: str, s2: str) -> bool:
3 diff = []
4 for i in range(len(s1)):
5 if s1[i] != s2[i]:
6 if len(diff) == 2:
7 return False
8 diff.append(i)
9 if not diff:
10 return True
11 if len(diff) != 2:
12 return False
13 a, b = diff
14 return s1[a] == s2[b] and s1[b] == s2[a]1class Solution {
2 public boolean areAlmostEqual(String s1, String s2) {
3 int[] diff = new int[2];
4 int count = 0;
5 for (int i = 0; i < s1.length(); i++) {
6 if (s1.charAt(i) != s2.charAt(i)) {
7 if (count == 2) return false;
8 diff[count++] = i;
9 }
10 }
11 if (count == 0) return true;
12 if (count != 2) return false;
13 int a = diff[0], b = diff[1];
14 return s1.charAt(a) == s2.charAt(b) && s1.charAt(b) == s2.charAt(a);
15 }
16}1class Solution {
2public:
3 bool areAlmostEqual(string s1, string s2) {
4 int diff[2];
5 int count = 0;
6 for (int i = 0; i < (int)s1.size(); i++) {
7 if (s1[i] != s2[i]) {
8 if (count == 2) return false;
9 diff[count++] = i;
10 }
11 }
12 if (count == 0) return true;
13 if (count != 2) return false;
14 int a = diff[0], b = diff[1];
15 return s1[a] == s2[b] && s1[b] == s2[a];
16 }
17};Time and space complexity
O(n)
One pass over the strings, and it can stop early at the third mismatch.
O(1)
Only two indices are ever stored.
Other approaches
Try every swap (time O(n^3), space O(n))
Swap every pair of positions in s2 and compare with s1. Correct but wasteful, since only the mismatched positions can matter.
Count letters plus count mismatches (time O(n), space O(1))
Check that both strings have the same letter counts and that the number of mismatched positions is 0 or 2. Works, but needs a 26-slot count array and a second pass.
Common mistakes
- Returning false when the strings are already equal. Zero swaps is allowed, so equal strings are a true case.
- Treating a single mismatch as fixable. No swap can change exactly one position.
- Checking only that the two mismatched columns hold the same set of letters in one direction. Both crossings, s1[a] == s2[b] and s1[b] == s2[a], must hold.
Frequently asked questions
Does it matter whether I swap in s1 or in s2?
No. Swapping positions a and b in s1 makes the strings equal exactly when swapping the same positions in s2 does, because both lead to the same crossing condition.
Why can I stop at the third mismatch?
A single swap touches two positions, so three positions that need to change can never all be fixed. Any further scanning cannot change the answer.
What about swapping a position with itself?
That is the zero-change swap. It covers the case where the strings are already equal, which is why an empty diff returns true.