Open In App
Related Articles

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

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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” 

 After removing  the elements which are the same and have the same index in both the strings. We have string A=”SS” and B=”GG”.

The new strings are of length two and both the elements in each string are same.Hence swapping is possible.
Input: A = “GEEKSFORGEEKS”, B = “THESUPERBSITE” 
Output: No 
 


 

Brute Force Approach:

  1. Initialize a boolean variable flag as false.
  2. Iterate through every character in string A and for each character, iterate through every character in string B.
  3. For each pair of characters (one from A and one from B), swap the characters and check if the two strings become equal. If they do, set the flag to true and break out of both loops.
  4. If the flag is true, print “Yes”, else print “No”.
     

Below is the implementation of the above approach: 

C++

// 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)
{
    bool flag = false;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            swap(a[i], b[j]);
            if (a == b) {
                flag = true;
                break;
            }
            swap(a[i], b[j]);
        }
        if (flag) break;
    }
    return flag;
}
 
 
// Driver code
int main()
{
    string A = "SEEKSFORGEEKS";
    string B = "GEEKSFORGEEKG";
     
    if (canBeEqual(A, B, A.size()))
        printf("Yes");
    else
        printf("No");
}

                    

Java

import java.util.*;
 
public class Main {
    // Function that returns true if the string can be made equal after one swap
    static boolean canBeEqual(String a, String b, int n) {
        boolean flag = false;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                char[] aChars = a.toCharArray();
                char[] bChars = b.toCharArray();
                char temp = aChars[i];
                aChars[i] = bChars[j];
                bChars[j] = temp;
                a = new String(aChars);
                b = new String(bChars);
                if (a.equals(b)) {
                    flag = true;
                    break;
                }
                // Swap back to undo the previous swap
                temp = aChars[i];
                aChars[i] = bChars[j];
                bChars[j] = temp;
                a = new String(aChars);
                b = new String(bChars);
            }
            if (flag) break;
        }
        return flag;
    }
 
    // Driver code
    public static void main(String[] args) {
        String A = "SEEKSFORGEEKS";
        String B = "GEEKSFORGEEKG";
         
        if (canBeEqual(A, B, A.length())) {
            System.out.println("Yes");
        } else {
            System.out.println("No");
        }
    }
}

                    

Python3

# Python3 implementation of the approach
 
# Function that returns true if the string
# can be made equal after one swap
def canBeEqual(a, b, n):
    flag = False
    for i in range(n):
        for j in range(n):
            a_list = list(a)
            b_list = list(b)
            a_list[i], b_list[j] = b_list[j], a_list[i]
            if "".join(a_list) == "".join(b_list):
                flag = True
                break
            a_list[i], b_list[j] = b_list[j], a_list[i]
        if flag:
            break
    return flag
 
# Driver code
if __name__ == "__main__":
    A = "SEEKSFORGEEKS"
    B = "GEEKSFORGEEKG"
 
    if canBeEqual(A, B, len(A)):
        print("Yes")
    else:
        print("No")

                    

C#

using System;
 
public class Program {
    // Function that returns true if the string
    // can be made equal after one swap
    public static bool CanBeEqual(string a, string b, int n)
    {
        bool flag = false;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                char[] arr1 = a.ToCharArray();
                char[] arr2 = b.ToCharArray();
                char temp = arr1[i];
                arr1[i] = arr2[j];
                arr2[j] = temp;
                string s1 = new string(arr1);
                string s2 = new string(arr2);
                if (s1 == s2) {
                    flag = true;
                    break;
                }
            }
            if (flag)
                break;
        }
        return flag;
    }
 
    // Driver code
    public static void Main()
    {
        string A = "SEEKSFORGEEKS";
        string B = "GEEKSFORGEEKG";
        if (CanBeEqual(A, B, A.Length)) {
            Console.WriteLine("Yes");
        }
        else {
            Console.WriteLine("No");
        }
    }
}

                    

Javascript

// Javascript implementation of the approach
 
// Function that returns true if the string
// can be made equal after one swap
function canBeEqual(a, b, n) {
    let flag = false;
    for (let i = 0; i < n; i++) {
        for (let j = 0; j < n; j++) {
            let temp = a[i];
            a = a.slice(0, i) + b[j] + a.slice(i + 1);
            b = b.slice(0, j) + temp + b.slice(j + 1);
            if (a === b) {
                flag = true;
                break;
            }
            temp = a[i];
            a = a.slice(0, i) + b[j] + a.slice(i + 1);
            b = b.slice(0, j) + temp + b.slice(j + 1);
        }
        if (flag) break;
    }
    return flag;
}
 
// Driver code
let A = "SEEKSFORGEEKS";
let B = "GEEKSFORGEEKG";
 
if (canBeEqual(A, B, A.length))
    console.log("Yes");
else
    console.log("No");

                    

Output
Yes

Time Complexity: O(N^2), where N is the length of the input strings A and B. This is because the code uses two nested loops to try every possible pair of character swaps.

Auxiliary Space: The space complexity of the implementation is O(1), as it uses a constant amount of extra space for variables regardless of the size of the input strings.

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

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

                    

Java

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

                    

Python3

# 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")

                    

C#

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

                    

Javascript

<script>
// Javascript implementation of the approach
 
// Function that returns true if the string
// can be made equal after one swap
function 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 code
let 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>

                    

Output
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.



Last Updated : 13 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads