Check if One String Swap Can Make Strings Equal
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 <= 100s1.length == s2.lengths1ands2contain 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.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
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.
| Approach | Time | Space |
|---|---|---|
| Brute force (try every swap) | O(n³) | O(n) |
| Letter counts and mismatch count | O(n) | O(1) |
| Optimal (remember the two mismatches) | O(n) | O(1) |
1Brute force (try every swap)
O(n³)There are about n² / 2 pairs, and each comparison with s2 reads all n characters.O(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.
- If s1 equals s2, return true.
- Copy s1 into a character array a.
- 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.
- 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;
}
}class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
if s1 == s2:
return True
a = list(s1)
n = len(a)
for i in range(n):
for j in range(i + 1, n):
a[i], a[j] = a[j], a[i]
same = "".join(a) == s2
a[i], a[j] = a[j], a[i]
if same:
return True
return Falseclass Solution {
public:
bool areAlmostEqual(string s1, string s2) {
if (s1 == s2) return true;
string a = s1;
int n = a.size();
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
swap(a[i], a[j]);
bool same = a == s2;
swap(a[i], a[j]);
if (same) return true;
}
}
return false;
}
};function areAlmostEqual(s1, s2) {
if (s1 === s2) return true;
const a = s1.split("");
const n = a.length;
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
[a[i], a[j]] = [a[j], a[i]];
const same = a.join("") === s2;
[a[i], a[j]] = [a[j], a[i]];
if (same) return true;
}
}
return false;
}2Letter counts and mismatch count
O(n)One pass over the strings plus a fixed loop over 26 counters.O(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].
- Keep 26 counters and a mismatch counter diff.
- 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].
- If any counter is not zero, return false.
- 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;
}
}class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
count = [0] * 26
diff = 0
for i in range(len(s1)):
count[ord(s1[i]) - ord("a")] += 1
count[ord(s2[i]) - ord("a")] -= 1
if s1[i] != s2[i]:
diff += 1
for c in count:
if c != 0:
return False
return diff == 0 or diff == 2class Solution {
public:
bool areAlmostEqual(string s1, string s2) {
int count[26] = {0};
int diff = 0;
for (int i = 0; i < (int) s1.size(); i++) {
count[s1[i] - 'a']++;
count[s2[i] - 'a']--;
if (s1[i] != s2[i]) diff++;
}
for (int c : count) {
if (c != 0) return false;
}
return diff == 0 || diff == 2;
}
};function areAlmostEqual(s1, s2) {
const count = new Array(26).fill(0);
let diff = 0;
for (let i = 0; i < s1.length; i++) {
count[s1.charCodeAt(i) - 97]++;
count[s2.charCodeAt(i) - 97]--;
if (s1[i] !== s2[i]) diff++;
}
for (const c of count) {
if (c !== 0) return false;
}
return diff === 0 || diff === 2;
}3Optimal (remember the two mismatches)
O(n)One pass over the strings, stopping early at the third mismatch.O(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].
- Set first = -1 and second = -1.
- 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.
- If first is still -1, return true (no mismatch).
- If second is still -1, return false (exactly one mismatch).
- 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);
}
}class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
first = second = -1
for i in range(len(s1)):
if s1[i] != s2[i]:
if first == -1:
first = i
elif second == -1:
second = i
else:
return False
if first == -1:
return True
if second == -1:
return False
return s1[first] == s2[second] and s1[second] == s2[first]class Solution {
public:
bool areAlmostEqual(string s1, string s2) {
int first = -1, second = -1;
for (int i = 0; i < (int) s1.size(); i++) {
if (s1[i] != s2[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[first] == s2[second] && s1[second] == s2[first];
}
};function areAlmostEqual(s1, s2) {
let first = -1, second = -1;
for (let i = 0; i < s1.length; i++) {
if (s1[i] !== s2[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[first] === s2[second] && s1[second] === s2[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.