Check if One String Swap Can Make Strings Equal

Easy Arrays & Hashing String Basics

Check if One String Swap Can Make Strings Equal is a easy arrays & hashing problem solved with the string basics pattern. The best approach, optimal (remember the two mismatches), runs in O(n) time and O(1) space. Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (try every swap) up.

Problem

You are given two strings s1 and s2 of the same length, made of lowercase English letters.

A swap picks two indexes of one string (they may be any two positions) and exchanges the characters stored there.

Return true if you can make the two strings equal by doing at most one swap on exactly one of them, and false otherwise. Doing no swap at all counts, so two strings that are already equal give true.

Examples

Example 1

Input
s1 = "clam", s2 = "calm"
Output
true
Why
The strings differ only at indexes 1 and 2. Swapping 'l' and 'a' in s1 turns "clam" into "calm".

Example 2

Input
s1 = "abcd", s2 = "badc"
Output
false
Why
All four positions differ. One swap changes at most two positions, so it can never fix four.

Example 3

Input
s1 = "loop", s2 = "loop"
Output
true
Why
The strings are already equal, and doing no swap at all is allowed.

Example 4

Input
s1 = "abcd", s2 = "abce"
Output
false
Why
Only index 3 differs. A swap moves two characters, so it cannot fix a single wrong position, and 'e' does not even occur in s1.

Constraints

  • 1 <= s1.length, s2.length <= 100
  • s1.length == s2.length
  • s1 and s2 contain only lowercase English letters

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (4 examples, or your own). Submit also runs 16 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Brute force (try every swap)O(n³)O(n)
Letter counts and mismatch countO(n)O(1)
Optimal (remember the two mismatches)O(n)O(1)

1Brute force (try every swap)

TimeO(n³)There are about n² / 2 pairs, and each comparison with s2 reads all n characters.
SpaceO(n)The character array copy of s1 (and the temporary string built for each comparison).

If the strings are already equal, the answer is true. Otherwise try every possible swap: for each pair of indexes i < j, swap s1[i] and s1[j], compare the result with s2, and swap back. If any swap makes them equal, return true.

  1. If s1 equals s2, return true.
  2. Copy s1 into a character array a.
  3. For every pair i < j: swap a[i] and a[j], check whether a now spells s2, then swap back. Return true on a match.
  4. If no swap worked, return false.
class Solution {
    public boolean areAlmostEqual(String s1, String s2) {
        if (s1.equals(s2)) return true;
        char[] a = s1.toCharArray();
        int n = a.length;
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                char t = a[i]; a[i] = a[j]; a[j] = t;
                boolean same = new String(a).equals(s2);
                t = a[i]; a[i] = a[j]; a[j] = t;
                if (same) return true;
            }
        }
        return false;
    }
}

2Letter counts and mismatch count

TimeO(n)One pass over the strings plus a fixed loop over 26 counters.
SpaceO(1)26 counters, whatever the length of the strings.

A swap never changes which letters a string contains, so s1 and s2 must use exactly the same letters the same number of times. A swap also changes exactly two positions, so the number of mismatched indexes must be 0 or 2. Both conditions together are enough: if the letter counts agree and only indexes i and j differ, the two letters s1 has there must be the two letters s2 has there, and since s1[i] is not s2[i], it has to be s2[j], and likewise s1[j] is s2[i].

  1. Keep 26 counters and a mismatch counter diff.
  2. For each index i: add one to the counter of s1[i], subtract one from the counter of s2[i], and add one to diff if s1[i] != s2[i].
  3. If any counter is not zero, return false.
  4. Return true if diff is 0 or 2.
class Solution {
    public boolean areAlmostEqual(String s1, String s2) {
        int[] count = new int[26];
        int diff = 0;
        for (int i = 0; i < s1.length(); i++) {
            count[s1.charAt(i) - 'a']++;
            count[s2.charAt(i) - 'a']--;
            if (s1.charAt(i) != s2.charAt(i)) diff++;
        }
        for (int c : count) {
            if (c != 0) return false;
        }
        return diff == 0 || diff == 2;
    }
}

3Optimal (remember the two mismatches)

TimeO(n)One pass over the strings, stopping early at the third mismatch.
SpaceO(1)Only the two stored indexes.

Walk both strings once and remember the first two indexes where they differ. A third mismatch means no single swap can help, so stop right away. At the end: no mismatch means the strings are already equal; exactly one mismatch cannot be fixed, because a swap always changes two positions; with exactly two, the swap works only if the letters cross over, s1[first] == s2[second] and s1[second] == s2[first].

  1. Set first = -1 and second = -1.
  2. For each index i where s1[i] != s2[i]: store i in first if it is empty, otherwise in second if it is empty, otherwise return false.
  3. If first is still -1, return true (no mismatch).
  4. If second is still -1, return false (exactly one mismatch).
  5. Return s1[first] == s2[second] && s1[second] == s2[first].
class Solution {
    public boolean areAlmostEqual(String s1, String s2) {
        int first = -1, second = -1;
        for (int i = 0; i < s1.length(); i++) {
            if (s1.charAt(i) != s2.charAt(i)) {
                if (first == -1) first = i;
                else if (second == -1) second = i;
                else return false;
            }
        }
        if (first == -1) return true;
        if (second == -1) return false;
        return s1.charAt(first) == s2.charAt(second) && s1.charAt(second) == s2.charAt(first);
    }
}

Edge cases to test

  • The strings are already equal: return true without any swap
  • Exactly one position differs: one swap always breaks a second position, so the answer is false
  • Exactly two positions differ but the letters do not cross over ("ab" vs "cd"): false
  • Three or more positions differ: false, a single swap touches only two positions
  • Same letters in a different order but too many mismatches ("abc" vs "bca"): false
  • Strings of length 1: true only if the two letters are equal

Hints

Hint 1

Ignore every index where s1 and s2 already agree. Only the mismatched indexes matter.

Hint 2

One swap changes exactly two positions. How many mismatches can it possibly repair?

Hint 3

With exactly two mismatches at i and j, the swap works only if s1[i] == s2[j] and s1[j] == s2[i].

FAQ

What is the best time complexity for Check if One String Swap Can Make Strings Equal?

Optimal (remember the two mismatches) runs in O(n) time and O(1) extra space. One pass over the strings, stopping early at the third mismatch.

Which pattern does Check if One String Swap Can Make Strings Equal use?

It is a arrays & hashing problem that uses the string basics pattern. Other problems with the same pattern: Longest Common Prefix, Minimum Changes To Make Alternating Binary String, Rotate String.

Is there a brute force solution for Check if One String Swap Can Make Strings Equal?

Yes. Brute force (try every swap) takes O(n³) time and O(n) space. If the strings are already equal, the answer is true.

Which edge cases should I test for Check if One String Swap Can Make Strings Equal?

The strings are already equal: return true without any swap; Exactly one position differs: one swap always breaks a second position, so the answer is false; Exactly two positions differ but the letters do not cross over ("ab" vs "cd"): false; Three or more positions differ: false, a single swap touches only two positions; Same letters in a different order but too many mismatches ("abc" vs "bca"): false; Strings of length 1: true only if the two letters are equal.