Leetcode•Jul 23, 2025
Buddy Strings
Hazrat Ali
Leetcode
Given two strings s
and goal
, return true
if you can swap two letters in s
so the result is equal to goal
, otherwise, return false
.
Swapping letters is defined as taking two indices i
and j
(0-indexed) such that i != j
and swapping the characters at s[i]
and s[j]
.
- For example, swapping at indices
0
and2
in"abcd"
results in"cbad"
.
Example 1:
Input: s = "ab", goal = "ba" Output: true Explanation: You can swap s[0] = 'a' and s[1] = 'b' to get "ba", which is equal to goal.
Example 2:
Input: s = "ab", goal = "ab" Output: false Explanation: The only letters you can swap are s[0] = 'a' and s[1] = 'b', which results in "ba" != goal.
Example 3:
Input: s = "aa", goal = "aa" Output: true Explanation: You can swap s[0] = 'a' and s[1] = 'a' to get "aa", which is equal to goal.
Solution
/**
* @param {string} A
* @param {string} B
* @return {boolean}
*/
const buddyStrings = (A, B) => {
if (!A || !B || A.length !== B.length) {
return false;
}
if (A === B) {
const count = {};
for (let c of A) {
count[c] = ~~count[c] + 1;
}
for (let c in count) {
if (count[c] > 1) {
return true;
}
}
return false;
}
let first = -1;
let second = -1;
for (let i = 0; i < A.length; i++) {
if (A[i] !== B[i]) {
if (first === -1) {
first = i;
} else if (second === -1) {
second = i;
} else {
return false;
}
}
}
return second !== -1 && A[first] === B[second] && A[second] === B[first];
};