# Blogs Hub

### by Sumit Chourasia | May 07, 2020 | Category :coding | Tags : algorithmडेटा-संरचनाstringleetcodeआसान #### Buddy Strings - मिनी टीवी

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

``````

Note:

``````0 <= A.length <= 20000

0 <= B.length <= 20000

A and B consist only of lowercase letters.``````

Solution:

``````using System;
using System.Collections.Generic;

namespace NetCoreCoding.LeetCode.String.Easy
{
public class BuddyStringsSoln
{
public BuddyStringsSoln()
{
}

public void execute()
{
var A = "abab";
var B = "abab";
var res = BuddyStrings(A,B);
}

public bool BuddyStrings(string A, string B)
{
if (A.Length != B.Length)
return false;

int diff = 0;
char[] diffChar = new char;
var set = new HashSet<char>();
for (int i = 0; i < A.Length; i++)
{
if (A[i] != B[i])
{
diff++;
if(diff==1)
{
diffChar = A[i];
diffChar = B[i];
}
else
{
if (diffChar != B[i] || diffChar != A[i])
return false;
}
}

}

if (A == B)
return set.Count < A.Length;

//case where all characters are same in
if (diff == 0 && set.Count == 1)
return true;

return diff == 2;
}
}
}
``````

Time Complexity: O(n)

Space Complexity: O(n)