Given two strings s
and goal
, return true
if you can swap two letters in s
such that the result is equal to goal
. Otherwise, return false
.
s
and goal
will be between 1 and 2 * 10^4.s
and goal
consist of lowercase letters.s
and goal
are different, the result should be false
.s
which allows a swap to still produce the same string.false
if the lengths of s
and goal
are different.s
is equal to goal
, we need to check if there is at least one duplicate character in s
which allows two positions to be swapped without changing the string.s
is not equal to goal
, we need to find all positions where the characters differ. For s
to be convertible into goal
by a single swap, there must be exactly two differing positions, and swapping these must result in goal
.#include <vector>
#include <string>
#include <unordered_set>
using namespace std;
bool buddyStrings(string s, string goal) {
// Step 1: Length check
if (s.length() != goal.length()) return false;
// Step 2: If the strings are equal, check for duplicates
if (s == goal) {
unordered_set<char> unique_chars;
for (char c : s) {
if (unique_chars.find(c) != unique_chars.end()) return true;
unique_chars.insert(c);
}
return false;
}
// Step 3: Collect position differences
vector<int> diff_positions;
for (int i = 0; i < s.length(); ++i) {
if (s[i] != goal[i]) diff_positions.push_back(i);
}
// Step 4: Check if there are exactly two differences and valid swap can fix it
return diff_positions.size() == 2 &&
s[diff_positions[0]] == goal[diff_positions[1]] &&
s[diff_positions[1]] == goal[diff_positions[0]];
}
This strategy ensures that we efficiently determine if it’s possible to transform s
into goal
via a single swap.
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?