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

Practice this problem in LeetCode: Click Here.

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++) {
        for(int i = 0; i < B.length(); i++) {
        //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
Please leave a comment below if you like this post or found some error, it will help me to improve my content.


Popular Posts from this Blog

Anti Diagonals - The Coding Shala

Shell Script to find sum, product and average of given numbers - The Coding Shala

LeetCode - Bulb Switcher Solution - The Coding Shala

New Year Chaos Solution - The Coding Shala

Sorting the Sentence LeetCode Solution - The Coding Shala