Magicsheet logo

Check if One String Swap Can Make Strings Equal

Easy
74.4%
Updated 6/1/2025

Check if One String Swap Can Make Strings Equal

What is this problem about?

The "Check if One String Swap Can Make Strings Equal" interview question asks whether two strings can be made identical by performing at most one swap of two characters in one of the strings. If the strings are already equal, it should return true (as zero swaps is "at most one").

Why is this asked in interviews?

This is a popular "Easy" level question at companies like Meta, Microsoft, and Amazon. It tests your ability to handle basic string manipulation, count occurrences, and identify differences between data sets. It’s a great test of efficiency—while you could try every possible swap (O(N2)O(N^2)), a much better solution exists that runs in linear time.

Algorithmic pattern used

The primary patterns are the Counting interview pattern and String Comparison. The logic is simple: for a single swap to fix everything, the strings must have exactly two indices where the characters differ, and those characters must be "mirrored" (e.g., s1[i]==s2[j]s1[i] == s2[j] and s1[j]==s2[i]s1[j] == s2[i]). Alternatively, if there are zero differences, they are already equal.

Example explanation

Imagine two strings: s1="bank"s1 = "bank", s2="kanb"s2 = "kanb".

  1. We compare them index by index.
  2. Index 0: 'b' vs 'k' (Different!)
  3. Index 1: 'a' vs 'a' (Same)
  4. Index 2: 'n' vs 'n' (Same)
  5. Index 3: 'k' vs 'b' (Different!)
  6. We have exactly two differences at indices 0 and 3.
  7. Is s1[0]==s2[3]s1[0] == s2[3]? Yes ('b' == 'b').
  8. Is s1[3]==s2[0]s1[3] == s2[0]? Yes ('k' == 'k'). Result: True.

Common mistakes candidates make

A common error is not checking if the character counts are the same. If the strings are "abc" and "def", there are three differences, but even if there were two, you could only swap if the characters involved were the same. Another mistake is forgetting to return true when the strings are already identical.

Interview preparation tip

Whenever you're asked to find if a small number of changes can fix a data structure, focus on the "mismatches." Count them first. If the number of mismatches exceeds the allowed number of operations, you can return early, which optimizes your code.

Similar Questions