Doubt in a question

Hi sir, I was trying a question on leetcode. Canyou pls look at my code and tell what am i doing wrong?

Link to Question:

Link to my Solution:

Please reply asap.

The logic you have used is partially right , do what is sort string a & b, then keep a count of mis matched characters, like if a[i]!=b[i] you keep a count. If count is exactly equal to 2 then return true, else for any other case, return false.
Also if length is not same for both string return false.

Sir, this approach will not satisfy Example 2 as Input: A = “ab”, B = “ab” Output: false

For this your count will be 0 right? So in it , you can check if count is 0 or 2, then you can return true else false.

Sir i have already tried this

we need to maintaion all test case which involves Test Case 1: A=“aa” B=“aa” for which output is true and Test case 2: A=“ab” and B=“ab” for which output is false

as in fos first test case, on swapping ‘a’ and ‘a’ we get B. But in test case 2, on swapping ‘a’ and ‘b’ we get A=“ba” where as B=“ab”, which are not same

Okay i got it, no need of sorting, rest everything told by me was right.
If A.length() != B.length() : no possible swap

If A == B , we need swap two same characters. Check is duplicated char in A .

In other cases, we find index for A[i] != B[i] . There should be only 2 diffs and it’s our one swap.

C++:

    bool buddyStrings(string A, string B) {
        if (A.length() != B.length()) return false;
        if (A == B && set<char>(A.begin(), A.end()).size() < A.size()) return true;
        vector<int> dif;
        for (int i = 0; i < A.length(); ++i) if (A[i] != B[i]) dif.push_back(i);
        return dif.size() == 2 && A[dif[0]] == B[dif[1]] && A[dif[1]] == B[dif[0]];
    }

It’s getting accepted

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.