889. Buddy Strings
EasySolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
Method Explanation
To determine if string goal can be obtained from string s by swapping exactly one pair of characters, we can break down the problem into a few distinct cases.
Solution
Buddy Strings in Python
class Solution:
def buddyStrings(self, s: str, goal: str) -> bool:
# Step 1: Check if lengths are different.
if len(s) != len(goal):
return False
# Step 2: Handle the case where s and goal are equal.
if s == goal:
# We must swap two identical characters.
# This is possible if there are any duplicate characters in s.
# A set's size will be smaller than the string's length if there are duplicates.
return len(set(s)) < len(s)
# Step 3: Handle the case where s and goal are different.
# Find the indices where s and goal differ.
diff_indices = []
for i in range(len(s)):
if s[i] != goal[i]:
diff_indices.append(i)
# We need exactly two differing positions for a single swap to work.
if len(diff_indices) != 2:
return False
# Let the two indices be i and j.
i, j = diff_indices[0], diff_indices[1]
# Check if swapping s[i] and s[j] makes the string equal to goal.
# This requires s[i] to be goal[j] and s[j] to be goal[i].
return s[i] == goal[j] and s[j] == goal[i]
Buddy Strings in Java
class Solution {
public boolean buddyStrings(String s, String goal) {
// Step 1: Check if lengths are different.
if (s.length() != goal.length()) {
return false;
}
// Step 2: Handle the case where s and goal are equal.
if (s.equals(goal)) {
// To make s equal to goal by one swap, we must swap two identical characters.
// This requires at least one character to appear twice in s.
int[] counts = new int[26];
for (char c : s.toCharArray()) {
counts[c - 'a']++;
if (counts[c - 'a'] > 1) {
return true; // Found a duplicate
}
}
// No duplicate characters found.
return false;
}
// Step 3: Handle the case where s and goal are different.
// We need to find exactly two positions where they differ.
List<Integer> diffIndices = new ArrayList<>();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != goal.charAt(i)) {
diffIndices.add(i);
}
}
// If the number of differing positions is not 2, one swap is not enough.
if (diffIndices.size() != 2) {
return false;
}
// Let the two differing indices be i and j.
int i = diffIndices.get(0);
int j = diffIndices.get(1);
// Check if swapping s[i] and s[j] results in goal.
// This means s[i] should be goal[j] and s[j] should be goal[i].
return s.charAt(i) == goal.charAt(j) && s.charAt(j) == goal.charAt(i);
}
}
Buddy Strings in C++
class Solution {
public:
bool buddyStrings(string s, string goal) {
// Step 1: Check if lengths are different. If so, impossible to be buddies.
if (s.length() != goal.length()) {
return false;
}
// Step 2: Handle the case where s and goal are equal.
if (s == goal) {
// We need to perform a swap. If s and goal are the same,
// we must swap two identical characters in s to keep it unchanged.
// This is only possible if s contains at least one duplicate character.
// An array can serve as a frequency map for lowercase letters.
int counts[26] = {0};
for (char c : s) {
counts[c - 'a']++;
if (counts[c - 'a'] > 1) {
// Found a duplicate character, so a swap is possible.
return true;
}
}
// No duplicate characters, so no swap can result in the same string.
return false;
}
// Step 3: Handle the case where s and goal are different.
// We need to find exactly two differing positions and check if a swap
// at these positions in s would make it equal to goal.
std::vector<int> diff_indices;
for (int i = 0; i < s.length(); ++i) {
if (s[i] != goal[i]) {
diff_indices.push_back(i);
}
}
// A single swap can only fix two differing positions.
// If there are not exactly two differences, it's impossible.
if (diff_indices.size() != 2) {
return false;
}
// Let the two differing indices be i and j.
int i = diff_indices[0];
int j = diff_indices[1];
// Check if swapping s[i] and s[j] results in goal.
// This means s[i] should be goal[j] and s[j] should be goal[i].
return s[i] == goal[j] && s[j] == goal[i];
}
};
Buddy Strings in TypeScript
function buddyStrings(s: string, goal: string): boolean {
// Step 1: Check if lengths are different.
if (s.length !== goal.length) {
return false;
}
// Step 2: Handle the case where s and goal are equal.
if (s === goal) {
// We must swap two identical characters. This requires duplicates.
const charSet = new Set<string>();
for (const char of s) {
if (charSet.has(char)) {
// Found a duplicate, so a valid swap is possible.
return true;
}
charSet.add(char);
}
// No duplicates found, so no swap can keep the string the same.
return false;
}
// Step 3: Handle the case where s and goal are different.
// Find differing indices.
const diffIndices: number[] = [];
for (let i = 0; i < s.length; i++) {
if (s[i] !== goal[i]) {
diffIndices.push(i);
}
}
// Must be exactly two differing positions for a single swap to fix.
if (diffIndices.length !== 2) {
return false;
}
// Let the indices be i and j.
const i = diffIndices[0];
const j = diffIndices[1];
// Check if swapping s[i] and s[j] results in goal.
// This means s[i] should be goal[j] and s[j] should be goal[i].
return s[i] === goal[j] && s[j] === goal[i];
};
More Easy LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.