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

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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 swap
bool 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 code
int 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

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of the approach
import java.util.*;
class GFG
{
      
// Function that returns true if the string
// can be made equal after one swap
static 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 code
public 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

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation of the approach
  
# Function that returns true if the string
# can be made equal after one swap
def 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 code
A = 'SEEKSFORGEEKS'
B = 'GEEKSFORGEEKG'
  
if (canBeEqual(A, B, len(A))):
    print("Yes")
else:
    print("No")

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation of the above approach 
using System;
using System.Collections.Generic;
  
class GFG
{
      
// Function that returns true if the string
// can be made equal after one swap
static 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 code
public 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

chevron_right


Output:

Yes


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.





Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.