Leetcode 1790. Check if One String Swap Can Make Strings Equal
Leetcode Problem 1790: Check if One String Swap Can Make Strings Equal
You are given two strings s1
and s2
of equal length. A string swap is defined as choosing two indices i
and j
(0-indexed) of a string and swapping the characters at these indices.
Return true
if it is possible to make both strings equal by performing at most one string swap on any of the strings. Otherwise, return false
.
s1
and s2
always of equal length?
To solve this problem, the approach can be as follows:
s1
is equal to s2
, we can return true
immediately.s1
makes it equal to s2
, then return true
.false
.Here is the implementation in C++:
#include <vector>
#include <string>
using namespace std;
bool areAlmostEqual(string s1, string s2) {
if (s1 == s2) return true;
vector<int> mismatchIndices;
for (int i = 0; i < s1.length(); ++i) {
if (s1[i] != s2[i]) {
mismatchIndices.push_back(i);
}
}
// There should be exactly 2 mismatch positions
if (mismatchIndices.size() != 2) return false;
int i1 = mismatchIndices[0], i2 = mismatchIndices[1];
// Swap characters at these two positions in s1
swap(s1[i1], s1[i2]);
// Check if they become equal
return s1 == s2;
}
The time complexity of this solution is O(n), where n
is the length of the input strings. The reason is that we are performing a single pass to compare the strings and store mismatched indices, and another very small constant-time operation to check and swap characters if needed. This makes the operation as efficient as possible for this problem.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?