Check if two strings can be made equal by swapping one character among each other
Last Updated :
13 Apr, 2023
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:
- Initialize a boolean variable flag as false.
- Iterate through every character in string A and for each character, iterate through every character in string B.
- 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.
- 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");
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>
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.
Similar Reads
Check if two strings can be made equal by swapping pairs of adjacent characters
Given two strings A and B of length N and M respectively and an array arr[] consisting of K integers, the task is to check if the string B can be obtained from the string A by swapping any pair of adjacent characters of the string A any number of times such that the swapped indices are not present i
15+ min read
Check if a string can be made equal to another string by swapping or replacement of characters
Given two strings S1 and S2, the task is to check if string S1 can be made equal to string S2 by swapping any pair of characters replacing any character in the string S1. If it is possible to make the string S1 equal to S2, then print "Yes". Otherwise, print "No". Examples: Input: S1 = âabcâ, S2 = â
8 min read
Check if two binary strings can be made equal by swapping pairs of unequal characters
Given two binary strings S1 and S2 of length N (1 ? N ? 105), the task is to check if it is possible to convert the string S1 to S2 by performing the following operations any number of times: Select any two indices i and j (1 ? i < j ? N) such that S1[i] is â0â and S1[j] is â1â.Swap S1[i] with S1
12 min read
Check if characters of one string can be swapped to form other
Two strings are given, we need to find whether we can form second string by swapping the character of the first string. Examples: Input : str1 = "geeksforgeeks" str2 = "geegeeksksfor" Output : YES Input : str1 = "geeksfor" str2 = "geeekfor" Output : NO First of all, we will find the length of string
6 min read
Check if given strings can be made same by swapping two characters of same or different strings
Given an array of equal-length strings, arr[] of size N, the task is to check if all the strings can be made equal by repeatedly swapping any pair of characters of same or different strings from the given array. If found to be true, then print "YES". Otherwise, print "NO". Examples: Input: arr[] = {
11 min read
Check if number of distinct characters in 2 Strings can be made equal
Given two strings A and B of lowercase English letters of lengths N and M respectively. Check whether the number of distinct characters in both strings A and B can be made equal by applying the operation at most one time. Where operation is: Choose any index i such that 0 ⤠i ⤠N from string A and i
15 min read
Check if all characters of a string can be made equal by increments or decrements
Given a string S consisting of N lowercase alphabets, the task is to check if it is possible to make all characters of the string S equal by incrementing and decrementing any two characters from the given string by 1. If it is possible to make all the characters the same, then print "Yes". Otherwise
5 min read
Check if a two character string can be made using given words
Given a string of two characters and n distinct words of two characters. The task is to find if it is possible to arrange given words in such a way that the concatenated string has the given two character string as a substring. We can append a word multiple times. Examples: Input : str = "ya" words[
6 min read
Check if String T can be made Substring of S by replacing given characters
Given two strings S and T and a 2D array replace[][], where replace[i] = {oldChar, newChar} represents that the character oldChar of T is replaced with newChar. The task is to find if it is possible to make string T a substring of S by replacing characters according to the replace array. Note: Each
9 min read
Check if characters of a given string can be used to form any N equal strings
Given a string S and an integer N, the task is to check if it is possible to generate any string N times from the characters of the given string or not. If it is possible, print Yes. Otherwise, print No. Examples: Input: S = "caacbb", N = 2Output: YesExplanation: All possible strings that can be gen
5 min read