easy Buddy Strings
Problem Statement
Given two strings a and b, return true if they can be considered "buddy strings". Otherwise, return false.
Two strings are buddy strings if you can swap any two letters in one string to make it equal to the other string.
Examples
-
Example 1:
- Input:
a = "xy", b = "yx" - Expected Output: true
- Justification: Swapping 'x' and 'y' in string
aresults in "yx", which matches stringb.
- Input:
-
Example 2:
- Input:
a = "ab", b = "cd" - Expected Output: false
- Justification: There are differences at every position, and swapping any characters in
acannot make it equal tob.
- Input:
-
Example 3:
- Input:
a = "abcde", b = "acbde" - Expected Output: true
- Justification: Swapping 'b' and 'c' in string
aresults in "acbde", which matches stringb.
- Input:
Try it yourself
Try solving this question here:
✅ Solution Buddy Strings
Problem Statement
Given two strings a and b, return true if they can be considered "buddy strings". Otherwise, return false.
Two strings are buddy strings if you can swap any two letters in one string to make it equal to the other string.
Examples
-
Example 1:
- Input:
a = "xy", b = "yx" - Expected Output: true
- Justification: Swapping 'x' and 'y' in string
aresults in "yx", which matches stringb.
- Input:
-
Example 2:
- Input:
a = "ab", b = "cd" - Expected Output: false
- Justification: There are differences at every position, and swapping any characters in
acannot make it equal tob.
- Input:
-
Example 3:
- Input:
a = "abcde", b = "acbde" - Expected Output: true
- Justification: Swapping 'b' and 'c' in string
aresults in "acbde", which matches stringb. So, both strings are buddy strings.
- Input:
Solution
To solve this problem, we start by comparing the lengths of the two strings. If their lengths differ, they cannot be buddy strings. For strings of equal length, we track the positions where they differ. If there are no differences and the first string has at least one repeating character, it means a swap could occur within the string to make it its own buddy string. If there are exactly two differences, we check if swapping the characters at these positions in one string makes the two strings equal. This approach ensures we accurately identify buddy strings by addressing both scenarios where strings are initially equal or need a specific swap to become equal.
Our approach is effective because it minimizes the number of checks needed to determine if two strings are buddy strings. By first checking the length, then the positions of difference, and finally the conditions for being buddy strings, we efficiently narrow down the possibilities with minimal computational overhead. This method balances thoroughness with efficiency, making it suitable for a wide range of inputs.
Step-by-step Algorithm
-
Initial Length Check:
- If
a.lengthis not equal tob.length, return false immediately, as strings of different lengths cannot be buddy strings.
- If
-
Handle Identical Strings:
- If the strings
aandbare identical, then for them to be buddy strings, there must be at least one character inathat appears more than once. Use a frequency count array or a set to check for repeating characters. If a repeat is found, return true.
- If the strings
-
Identify and Record Differences:
- If
aandbare not identical, iterate through both strings simultaneously to compare characters at each position. - Record the indices where
aandbdiffer. Use two variables,firstandsecond, initialized to -1, to store these indices. - If more than two differences are found, return false as a swap cannot resolve more than two differences.
- If
-
Check for Exactly Two Differences:
- After identifying the indices of differences, check if swapping the characters at these positions in
awould make it equal tob. This means that the character atfirstindex inashould match the character atsecondindex inband vice versa.
- After identifying the indices of differences, check if swapping the characters at these positions in
-
Final Verification:
- If the conditions in step 4 are satisfied, return true, indicating that the strings are buddy strings by a single swap.
- Otherwise, return false.
Algorithm Walkthrough
Consider the input a = "abcde", b = "acbde".
-
Initial Length Check:
- Both strings
aandbare of the same length. This check passes, allowing us to proceed to the next step.
- Both strings
-
Handle Identical Strings:
- The strings
aandbare not identical, so we move to the next step. There's no need to check for repeating characters since the strings differ.
- The strings
-
Identify and Record Differences:
- As we iterate through both strings from the beginning, they match at the first position. At the second position, we encounter a difference ('b' in
avs 'c' inb), so we recordfirst = 1. - Continuing, we find another difference at the third position ('c' in
avs 'b' inb), so we recordsecond = 2. The rest of the characters match in both strings. - There are exactly two differences, and no more, which is what we need for a potential swap to make
aandbequal.
- As we iterate through both strings from the beginning, they match at the first position. At the second position, we encounter a difference ('b' in
-
Check for Exactly Two Differences:
- With
first = 1andsecond = 2, we check if swapping the characters at these positions inawould make it equal tob. Specifically, we're looking to see if after the swap,a[first]equalsb[second]anda[second]equalsb[first]. - Before the swap:
a = "abcde",b = "acbde" - After a hypothetical swap in
a(swapping 'b' and 'c'):awould become "acbde". - This swapped version of
amatchesbexactly.
- With
-
Final Verification:
- Since swapping 'b' and 'c' in
amakes it identical tob, the strings are buddy strings. Therefore, we return true.
- Since swapping 'b' and 'c' in
Code
public class Solution {
// Method to check if two strings are buddy strings
public boolean buddyStrings(String a, String b) {
// Check for length equality
if (a.length() != b.length()) return false;
// Handling identical strings
if (a.equals(b)) {
int[] count = new int[26]; // Frequency count for characters
for (int i = 0; i < a.length(); i++) {
count[a.charAt(i) - 'a']++;
if (count[a.charAt(i) - 'a'] > 1) return true; // Found a repeating character
}
return false; // No repeating characters
} else {
// Identifying positions where characters differ
int first = -1, second = -1;
for (int i = 0; i < a.length(); i++) {
if (a.charAt(i) != b.charAt(i)) {
if (first == -1) first = i; // First difference
else if (second == -1) second = i; // Second difference
else return false; // More than two differences
}
}
// Checking if swapping makes the strings equal
return (
second != -1 &&
a.charAt(first) == b.charAt(second) &&
a.charAt(second) == b.charAt(first)
);
}
}
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.buddyStrings("xy", "yx")); // true
System.out.println(solution.buddyStrings("ab", "cd")); // false
System.out.println(solution.buddyStrings("abcde", "acbde")); // true
}
}
Complexity Analysis
- Time Complexity:
where n is the length of the strings, as the algorithm iterates over the strings at most once. - Space Complexity:
for checking differences and in the worst case when the strings are identical to store character frequencies. However, because the character set is limited (assuming ASCII), this can also be considered in practical scenarios where the alphabet size is fixed.
🤖 Don't fully get this? Learn it with Claude
Stuck on Buddy Strings? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Buddy Strings** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Buddy Strings** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Buddy Strings**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Buddy Strings**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.