LeetCode 859: Buddy Strings Solution
Master LeetCode problem 859 (Buddy Strings), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
859. Buddy Strings
Problem Explanation
Explanation
To solve this problem, we need to check if we can swap two characters in string s to make it equal to string goal. We can have two cases:
- If
sandgoalare equal, we need to check if there are at least two characters that are the same ins. If so, we can swap these two characters to get the same string. - If
sandgoalare not equal, we need to check if there are exactly two pairs of characters that are different betweensandgoal. If so, we can swap these two pairs to makesequal togoal.
Algorithm
- If the lengths of
sandgoalare not equal, return false. - If
sis equal togoal, check if there are at least two characters that are the same insby using a set. - If
sis not equal togoal, iterate over both strings and store the indices of different characters in separate lists. Check if there are exactly two pairs of different characters. - Return true if any of the conditions are met, otherwise return false.
Time complexity: O(n) Space complexity: O(n)
Solution Code
class Solution {
public boolean buddyStrings(String s, String goal) {
if (s.length() != goal.length()) {
return false;
}
if (s.equals(goal)) {
Set<Character> set = new HashSet<>();
for (char c : s.toCharArray()) {
if (set.contains(c)) {
return true;
}
set.add(c);
}
} else {
List<Integer> diffIndices = new ArrayList<>();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != goal.charAt(i)) {
diffIndices.add(i);
}
}
if (diffIndices.size() != 2) {
return false;
}
return s.charAt(diffIndices.get(0)) == goal.charAt(diffIndices.get(1)) && s.charAt(diffIndices.get(1)) == goal.charAt(diffIndices.get(0));
}
return false;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 859 (Buddy Strings)?
This page provides optimized solutions for LeetCode problem 859 (Buddy Strings) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 859 (Buddy Strings)?
The time complexity for LeetCode 859 (Buddy Strings) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 859 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 859 in Java, C++, or Python.