859. Buddy Strings LeetCode Solution

In this guide, you will get 859. Buddy Strings LeetCode Solution with the best time and space complexity. The solution to Buddy Strings problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Buddy Strings solution in C++
  4. Buddy Strings solution in Java
  5. Buddy Strings solution in Python
  6. Additional Resources
859. Buddy Strings LeetCode Solution image

Problem Statement of Buddy Strings

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 and 2 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.

Constraints:

1 <= s.length, goal.length <= 2 * 104
s and goal consist of lowercase letters.

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(n)

859. Buddy Strings LeetCode Solution in C++

class Solution {
 public:
  bool buddyStrings(string s, string goal) {
    if (s.length() != goal.length())
      return false;
    if (s == goal && hasDuplicateLetters(s))
      return true;

    vector<int> diffIndices;

    for (int i = 0; i < s.length(); ++i)
      if (s[i] != goal[i])
        diffIndices.push_back(i);

    return diffIndices.size() == 2 &&
           s[diffIndices[0]] == goal[diffIndices[1]] &&
           s[diffIndices[1]] == goal[diffIndices[0]];
  }

 private:
  bool hasDuplicateLetters(const string& s) {
    vector<int> count(26);
    for (const char c : s)
      ++count[c - 'a'];
    return ranges::any_of(count, [](int freq) { return freq > 1; });
  }
};
/* code provided by PROGIEZ */

859. Buddy Strings LeetCode Solution in Java

class Solution {
  public boolean buddyStrings(String s, String goal) {
    if (s.length() != goal.length())
      return false;
    if (s.equals(goal) && hasDuplicateLetters(s))
      return true;

    List<Integer> diffIndices = new ArrayList<>();

    for (int i = 0; i < s.length(); ++i)
      if (s.charAt(i) != goal.charAt(i))
        diffIndices.add(i);

    return diffIndices.size() == 2 &&
        s.charAt(diffIndices.get(0)) == goal.charAt(diffIndices.get(1)) &&
        s.charAt(diffIndices.get(1)) == goal.charAt(diffIndices.get(0));
  }

  private boolean hasDuplicateLetters(String s) {
    int[] count = new int[26];
    for (char c : s.toCharArray())
      ++count[c - 'a'];
    return Arrays.stream(count).anyMatch(freq -> freq > 1);
  }
}
// code provided by PROGIEZ

859. Buddy Strings LeetCode Solution in Python

class Solution:
  def buddyStrings(self, s: str, goal: str) -> bool:
    if len(s) != len(goal):
      return False
    if s == goal and len(set(s)) < len(s):
      return True
    diffIndices = [i for i, (a, b) in enumerate(zip(s, goal))
                   if a != b]
    return (len(diffIndices) == 2 and
            s[diffIndices[0]] == goal[diffIndices[1]] and
            s[diffIndices[1]] == goal[diffIndices[0]])
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.