Check if a given string can be converted to another by given possible swaps

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:

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:



Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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";
    }
}
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

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

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

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

Output: 
True

 

Time Complexity: O(N + M + 256) 
Auxiliary Space: O(256)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




Article Tags :
Practice Tags :