### LeetCode - Buddy Strings Solution - The Coding Shala

Home >> LeetCode >> Buddy Strings

In this post, we will learn how to solve LeetCode's Buddy Strings problem and will implement its solution in Java language.

## Buddy Strings Problem

Given two strings A and B of lowercase letters, return true if and only if we can swap two letters in A so that the result equals B.

Example 1:
Input: A = "ab", B = "ba"
Output: true

Example 2:
Input: A = "ab", B = "ab"
Output: false

Example 3:
Input: A = "aa", B = "aa"
Output: true

Example 4:
Input: A = "aaaaaaabc", B = "aaaaaaacb"
Output: true

Example 5:
Input: A = "", B = "aa"
Output: false

## Buddy Strings Java Solution

Approach 1:
Here, we need to check three things:
1. First, if both strings have different length then there is no possible swaps.
2. if both strings are the same then check if there are duplicate then we can swap duplicate char to make buddy strings.
3. The third case is A[i] != B[i], then there should be exactly two swap.
Java Program:

```class Solution {
public boolean buddyStrings(String A, String B) {
int[] arrA = new int[26];
int[] arrB = new int[26];
if(A.length() != B.length()) return false;

for(int i = 0; i < A.length(); i++) {
arrA[A.charAt(i)-'a']++;
}

for(int i = 0; i < B.length(); i++) {
arrB[B.charAt(i)-'a']++;
}

//check number of chars are same in both strings
for(int i=0; i<26; i++) {
if(arrA[i] != arrB[i]) return false;
}

//check number of different char
int count = 0;
for(int i=0; i<A.length(); i++){
if(A.charAt(i) != B.charAt(i)) count++;
}

//if only two then true
if(count == 2) return true;

//if both strings are same and any char are more than once
if(count == 0) {
for(int i=0; i<26; i++) {
if(arrA[i] > 1) return true;
}
}

return false;
}
}
```

Other Posts You May Like