Check if two strings can be made equal by swapping one character among each other

23 May, 2022
Given two strings A and B of length N, the task is to check whether the two strings can be made equal by swapping any character of A with any other character of B only once.Examples:  
Input: A = “SEEKSFORGEEKS”, B = “GEEKSFORGEEKG” Output: Yes “SEEKSFORGEEKS” and “GEEKSFORGEEKG” can be swapped to make both the strings equal.Input: A = “GEEKSFORGEEKS”, B = “THESUPERBSITE” Output: No  
 
Approach: First omit the elements which are the same and have the same index in both the strings. Then if the new strings are of length two and both the elements in each string are the same then only the swap is possible.Below is the implementation of the above approach:  
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that returns true if the string// can be made equal after one swapbool canBeEqual(string a, string b, int n){    // A and B are new a and b    // after we omit the same elements    vector<char> A, B;     // Take only the characters which are    // different in both the strings    // for every pair of indices    for (int i = 0; i < n; i++)    {         // If the current characters differ        if (a[i]!= b[i])        {            A.push_back(a[i]);            B.push_back(b[i]);        }    }         // The strings were already equal    if (A.size() == B.size() and        B.size() == 0)        return true;     // If the lengths of the    // strings are two    if (A.size() == B.size() and        B.size() == 2)    {         // If swapping these characters        // can make the strings equal        if (A[0] == A[1] and B[0] == B[1])            return true;    }    return false;} // Driver codeint main(){    string A = "SEEKSFORGEEKS";    string B = "GEEKSFORGEEKG";         if (canBeEqual(A, B, A.size()))        printf("Yes");    else        printf("No");} // This code is contributed by Mohit Kumar
// Java implementation of the approachimport java.util.*;class GFG{     // Function that returns true if the string// can be made equal after one swapstatic boolean canBeEqual(char []a,                          char []b, int n){    // A and B are new a and b    // after we omit the same elements    Vector<Character> A = new Vector<>();    Vector<Character> B = new Vector<>();     // Take only the characters which are    // different in both the strings    // for every pair of indices    for (int i = 0; i < n; i++)    {         // If the current characters differ        if (a[i] != b[i])        {            A.add(a[i]);            B.add(b[i]);        }    }         // The strings were already equal    if (A.size() == B.size() &&        B.size() == 0)        return true;     // If the lengths of the    // strings are two    if (A.size() == B.size() &&        B.size() == 2)    {         // If swapping these characters        // can make the strings equal        if (A.get(0) == A.get(1) &&            B.get(0) == B.get(1))            return true;    }    return false;} // Driver codepublic static void main(String[] args){    char []A = "SEEKSFORGEEKS".toCharArray();    char []B = "GEEKSFORGEEKG".toCharArray();         if (canBeEqual(A, B, A.length))        System.out.printf("Yes");    else        System.out.printf("No");}} // This code is contributed by Rajput-Ji
# Python3 implementation of the approach # Function that returns true if the string# can be made equal after one swapdef canBeEqual(a, b, n):    # A and B are new a and b    # after we omit the same elements    A =[]    B =[]         # Take only the characters which are    # different in both the strings    # for every pair of indices    for i in range(n):             # If the current characters differ        if a[i]!= b[i]:            A.append(a[i])            B.append(b[i])                 # The strings were already equal    if len(A)== len(B)== 0:        return True         # If the lengths of the    # strings are two    if len(A)== len(B)== 2:             # If swapping these characters        # can make the strings equal        if A[0]== A[1] and B[0]== B[1]:            return True         return False # Driver codeA = 'SEEKSFORGEEKS'B = 'GEEKSFORGEEKG' if (canBeEqual(A, B, len(A))):    print("Yes")else:    print("No")
// C# implementation of the above approachusing System;using System.Collections.Generic; class GFG{     // Function that returns true if the string// can be made equal after one swapstatic Boolean canBeEqual(char []a,                          char []b, int n){    // A and B are new a and b    // after we omit the same elements    List<char> A = new List<char>();    List<char> B = new List<char>();     // Take only the characters which are    // different in both the strings    // for every pair of indices    for (int i = 0; i < n; i++)    {         // If the current characters differ        if (a[i] != b[i])        {            A.Add(a[i]);            B.Add(b[i]);        }    }         // The strings were already equal    if (A.Count == B.Count &&        B.Count == 0)        return true;     // If the lengths of the    // strings are two    if (A.Count == B.Count &&        B.Count == 2)    {         // If swapping these characters        // can make the strings equal        if (A[0] == A[1] &&            B[0] == B[1])            return true;    }    return false;} // Driver codepublic static void Main(String[] args){    char []A = "SEEKSFORGEEKS".ToCharArray();    char []B = "GEEKSFORGEEKG".ToCharArray();         if (canBeEqual(A, B, A.Length))        Console.WriteLine("Yes");    else        Console.WriteLine("No");}} // This code is contributed by PrinciRaj1992
<script>// Javascript implementation of the approach // Function that returns true if the string// can be made equal after one swapfunction canBeEqual(a,b,n){    // A and B are new a and b    // after we omit the same elements    let A = [];    let B = [];       // Take only the characters which are    // different in both the strings    // for every pair of indices    for (let i = 0; i < n; i++)    {           // If the current characters differ        if (a[i] != b[i])        {            A.push(a[i]);            B.push(b[i]);        }    }           // The strings were already equal    if (A.length == B.length &&        B.length == 0)        return true;       // If the lengths of the    // strings are two    if (A.length == B.length &&        B.length == 2)    {           // If swapping these characters        // can make the strings equal        if (A[0] == A[1] &&            B[0] == B[1])            return true;    }    return false;}// Driver codelet A = "SEEKSFORGEEKS".split("");let B = "GEEKSFORGEEKG".split(""); if (canBeEqual(A, B, A.length))    document.write("Yes");else    document.write("No");   // This code is contributed by unknown2108</script>
Yes
 
Time Complexity: O(N), where N is the size of the given strings.
Auxiliary Space: O(N), where N is the size of the given strings.
mohit kumar 29
Rajput-Ji
princiraj1992
unknown2108
samim2000
Constructive Algorithms
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different Methods to Reverse a String in C++
Python program to check if a string is palindrome or not
Check for Balanced Brackets in an expression (well-formedness) using Stack
KMP Algorithm for Pattern Searching
Longest Palindromic Substring | Set 1
Length of the longest substring without repeating characters
Top 50 String Coding Problems for Interviews
Check whether two strings are anagram of each other
Convert string to char array in C++
Reverse words in a given string