Check if a given string can be converted to another by given possible swaps
Last Updated :
19 May, 2021
Given two strings str1 and str2, the task is to check if a string str1 can be converted to string str2 by performing the following operations any number of times:
- Swap any two characters of str1.
- Swap all the occurrences of a character of str1 to all occurrences of any other distinct character of str1.
Examples:
Input: str1 = "xyyzzlll", str2 = "yllzzxxx"
Output: True
Explanation:
Swap all occurrences of str1[0] and str1[1] modifies str1 to "yxxzzlll"
Swap all occurrences of str1[1] and str1[5] modifies str1 to "yllzzxxx"
Since str1 and str2 are equal, therefore, the required output is True.
Input: str1 = "xyyzzavl", str2 = "yllzzvac"
Output: False
Approach: The problem can be solved using Greedy technique. Follow the steps below to solve the problem:
- Initialize two arrays, say hash1[256] and hash2[256] to store the frequency of each distinct element of str1 and str2 respectively.
- Initialize two sets, say st1 and st2 to store the distinct characters of str1 and str2.
- Traverse the string and store the frequency of each distinct character of str1 and str2.
- Sort hash1[] and hash2[] array.
- If st1 and st2 are not equal then print false.
- Traverse hash1[] and hash2[] array using variable i and check if the value of (hash1[i] != hash2[i]) is true or not. If found to be true then print False.
- Otherwise, print True.
Below is the implementation of the above approach:
C++
// C++ program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
bool checkStr1CanConStr2(string& str1,
string& str2)
{
// Stores length of str1
int N = str1.length();
// Stores length of str2
int M = str2.length();
// Stores distinct characters
// of str1
set<int> st1;
// Stores distinct characters
// of str2
set<int> st2;
// Stores frequency of
// each character of str1
int hash1[256] = { 0 };
// Traverse the string str1
for (int i = 0; i < N; i++) {
// Update frequency
// of str1[i]
hash1[str1[i]]++;
}
// Traverse the string str1
for (int i = 0; i < N; i++) {
// Insert str1[i]
// into st1
st1.insert(str1[i]);
}
// Traverse the string str2
for (int i = 0; i < M; i++) {
// Insert str1[i]
// into st1
st2.insert(str2[i]);
}
// If distinct characters in
// str1 and str2 are not same
if (st1 != st2) {
return false;
}
// Stores frequency of
// each character of str2
int hash2[256] = { 0 };
// Traverse the string str2
for (int i = 0; i < M; i++) {
// Update frequency
// of str2[i]
hash2[str2[i]]++;
}
// Sort hash1[] array
sort(hash1, hash1 + 256);
// Sort hash2[] array
sort(hash2, hash2 + 256);
// Traverse hash1[] and hash2[]
for (int i = 0; i < 256; i++) {
// If hash1[i] not
// equal to hash2[i]
if (hash1[i] != hash2[i]) {
return false;
}
}
return true;
}
// Driver Code
int main()
{
string str1 = "xyyzzlll";
string str2 = "yllzzxxx";
if (checkStr1CanConStr2(str1, str2)) {
cout << "True";
}
else {
cout << "False";
}
}
Java
// Java program to implement
// the above approach
import java.util.*;
class GFG{
static boolean checkStr1CanConStr2(String str1,
String str2)
{
// Stores length of str1
int N = str1.length();
// Stores length of str2
int M = str2.length();
// Stores distinct characters
// of str1
HashSet<Integer> st1 = new HashSet<>();
// Stores distinct characters
// of str2
HashSet<Integer> st2 = new HashSet<>();
// Stores frequency of
// each character of str1
int hash1[] = new int[256];
// Traverse the String str1
for (int i = 0; i < N; i++)
{
// Update frequency
// of str1[i]
hash1[str1.charAt(i)]++;
}
// Traverse the String str1
for (int i = 0; i < N; i++)
{
// Insert str1[i]
// into st1
st1.add((int)str1.charAt(i));
}
// Traverse the String str2
for (int i = 0; i < M; i++)
{
// Insert str1[i]
// into st1
st2.add((int)str2.charAt(i));
}
// If distinct characters in
// str1 and str2 are not same
if (!st1.equals(st2))
{
return false;
}
// Stores frequency of
// each character of str2
int hash2[] = new int[256];
// Traverse the String str2
for (int i = 0; i < M; i++)
{
// Update frequency
// of str2[i]
hash2[str2.charAt(i)]++;
}
// Sort hash1[] array
Arrays.sort(hash1);
// Sort hash2[] array
Arrays.sort(hash2);
// Traverse hash1[] and hash2[]
for (int i = 0; i < 256; i++)
{
// If hash1[i] not
// equal to hash2[i]
if (hash1[i] != hash2[i])
{
return false;
}
}
return true;
}
// Driver Code
public static void main(String[] args)
{
String str1 = "xyyzzlll";
String str2 = "yllzzxxx";
if (checkStr1CanConStr2(str1, str2))
{
System.out.print("True");
}
else
{
System.out.print("False");
}
}
}
// This code is contributed by 29AjayKumar
Python3
# Python3 program to implement
# the above approach
def checkStr1CanConStr2(str1, str2):
# Stores length of str1
N = len(str1)
# Stores length of str2
M = len(str2)
# Stores distinct characters
# of str1
st1 = set([])
# Stores distinct characters
# of str2
st2 = set([])
# Stores frequency of
# each character of str1
hash1 = [0] * 256
# Traverse the string str1
for i in range(N):
# Update frequency
# of str1[i]
hash1[ord(str1[i])] += 1
# Traverse the string str1
for i in range(N):
# Insert str1[i]
# into st1
st1.add(str1[i])
# Traverse the string str2
for i in range(M):
# Insert str1[i]
# into st1
st2.add(str2[i])
# If distinct characters in
# str1 and str2 are not same
if (st1 != st2):
return False
# Stores frequency of
# each character of str2
hash2 = [0] * 256
# Traverse the string str2
for i in range(M):
# Update frequency
# of str2[i]
hash2[ord(str2[i])] += 1
# Sort hash1[] array
hash1.sort()
# Sort hash2[] array
hash2.sort()
# Traverse hash1[] and hash2[]
for i in range(256):
# If hash1[i] not
# equal to hash2[i]
if (hash1[i] != hash2[i]):
return False
return True
# Driver Code
if __name__ == "__main__":
str1 = "xyyzzlll"
str2 = "yllzzxxx"
if (checkStr1CanConStr2(str1, str2)):
print("True")
else:
print("False")
# This code is contributed by chitranayal
C#
// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
class GFG{
static bool checkStr1CanConStr2(String str1,
String str2)
{
// Stores length of str1
int N = str1.Length;
// Stores length of str2
int M = str2.Length;
// Stores distinct characters
// of str1
HashSet<int> st1 = new HashSet<int>();
// Stores distinct characters
// of str2
HashSet<int> st2 = new HashSet<int>();
// Stores frequency of
// each character of str1
int []hash1 = new int[256];
// Traverse the String str1
for (int i = 0; i < N; i++)
{
// Update frequency
// of str1[i]
hash1[str1[i]]++;
}
// Traverse the String str1
for (int i = 0; i < N; i++)
{
// Insert str1[i]
// into st1
st1.Add(str1[i]);
}
// Traverse the String str2
for (int i = 0; i < M; i++)
{
// Insert str1[i]
// into st1
st2.Add(str2[i]);
}
// If distinct characters in
// str1 and str2 are not same
if (st1.Equals(st2))
{
return false;
}
// Stores frequency of
// each character of str2
int []hash2 = new int[256];
// Traverse the String str2
for (int i = 0; i < M; i++)
{
// Update frequency
// of str2[i]
hash2[str2[i]]++;
}
// Sort hash1[] array
Array.Sort(hash1);
// Sort hash2[] array
Array.Sort(hash2);
// Traverse hash1[] and hash2[]
for (int i = 0; i < 256; i++)
{
// If hash1[i] not
// equal to hash2[i]
if (hash1[i] != hash2[i])
{
return false;
}
}
return true;
}
// Driver Code
public static void Main(String[] args)
{
String str1 = "xyyzzlll";
String str2 = "yllzzxxx";
if (checkStr1CanConStr2(str1, str2))
{
Console.Write("True");
}
else
{
Console.Write("False");
}
}
}
// This code is contributed by 29AjayKumar
JavaScript
<script>
// Javascript program to implement
// the above approach
function checkStr1CanConStr2(str1, str2)
{
// Stores length of str1
var N = str1.length;
// Stores length of str2
var M = str2.length;
// Stores distinct characters
// of str1
var st1 = new Set();
// Stores distinct characters
// of str2
var st2 = new Set();
// Stores frequency of
// each character of str1
var hash1 = Array(256).fill(0);
// Traverse the string str1
for (var i = 0; i < N; i++) {
// Update frequency
// of str1[i]
hash1[str1[i].charCodeAt(0)]++;
}
// Traverse the string str1
for (var i = 0; i < N; i++) {
// Insert str1[i]
// into st1
st1.add(str1[i]);
}
// Traverse the string str2
for (var i = 0; i < M; i++) {
// Insert str1[i]
// into st1
st2.add(str2[i]);
}
// If distinct characters in
// str1 and str2 are not same
if (st1.size != st2.size) {
return false;
}
// Stores frequency of
// each character of str2
var hash2 = Array(256).fill(0);
// Traverse the string str2
for (var i = 0; i < M; i++) {
// Update frequency
// of str2[i]
hash2[str2[i].charCodeAt(0)]++;
}
// Sort hash1[] array
hash1.sort((a,b)=>a-b);
hash2.sort((a,b)=>a-b);
// Traverse hash1[] and hash2[]
for (var i = 0; i < 256; i++) {
// If hash1[i] not
// equal to hash2[i]
if (hash1[i] != hash2[i]) {
return false;
}
}
return true;
}
// Driver Code
var str1 = "xyyzzlll";
var str2 = "yllzzxxx";
if (checkStr1CanConStr2(str1, str2)) {
document.write( "True");
}
else {
document.write( "False");
}
</script>
Time Complexity: O(N + M + 256)
Auxiliary Space: O(256)
Similar Reads
Check if a string can be converted to another given string by removal of a substring Given two strings S and T of length N and M respectively, the task is to check if the string S can be converted to the string T by removing at most one substring of the string S. If found to be true, then print âYESâ. Otherwise, print âNOâ. Example: Input: S = âabcdefâ, T = âabcâ Output: YES Explana
7 min read
Check if one string can be converted to another Given two strings str and str1, the task is to check whether one string can be converted to other by using the following operation: Convert all the presence of a character by a different character. For example, if str = "abacd" and operation is to change character 'a' to 'k', then the resultant str
8 min read
Check if a string can be converted to another by swapping of adjacent characters of given type Given two strings str1 and str2 of size N consisting of only three characters A, B, and C, the task is to check whether the string str1 can be changed to str2 using the below operations: Replacing one occurrence of âBCâ with âCBâ i.e swap adjacent âBâ and âCâ.Replacing one occurrence of âCAâ with âA
7 min read
Check if a String can be converted to another by inserting character same as both neighbours Given 2 strings A and B . The task is to check if A can be converted into B by performing the following operation any number of times : Choose an index from 0 to N - 2 (suppose N is the length of A). If the character at ith index is equal to the character at (i + 1 )th index, then insert the same ch
9 min read
Check if one string can be converted to other using given operation Given two strings S and T of same length. The task is to determine whether or not we can build a string A(initially empty) equal to string T by performing the below operations. Delete the first character of S and add it at the front of A. Delete the first character of S and add it at the back of A.
15+ min read