Check if One String Swap Can Make Strings Equal (LeetCode 1790): Solution and Explanation

Easy
Hash Table
String
Counting

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

  1. Walk both strings together. Whenever s1[i] != s2[i], append i to diff.
  2. If diff already holds two indices when a new mismatch appears, return false right away.
  3. After the loop, return true if diff is empty.
  4. Return false if diff holds exactly one index.
  5. Otherwise let a, b = diff and return s1[a] == s2[b] and s1[b] == s2[a].

Step-by-step example

s1 = "bank", s2 = "kanb"
  1. Column 0: 'b' vs 'k' differ, so diff = [0].
  2. Column 1: 'a' vs 'a' match.
  3. Column 2: 'n' vs 'n' match.
  4. Column 3: 'k' vs 'b' differ, so diff = [0, 3].
  5. Exactly two mismatches: a = 0, b = 3.
  6. 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]
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

One pass over the strings, and it can stop early at the third mismatch.

Space

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.