Skip to content
Related Articles

Related Articles

Check if two strings can be made equal by swapping pairs of adjacent characters
  • Difficulty Level : Hard
  • Last Updated : 19 Apr, 2021

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 in the array arr[]. If it is possible to convert string A to string B, print “Yes”. Otherwise, print “No”.

Examples:

Input: A = “abcabka”, B = “acbakba”, arr[] = {0, 3, 6}
Output: Yes
Explanation:
Swap A1 and A2. Now the string becomes A = “acbabka”.
Swap A4 and A5. Now the string becomes A = “acbakba”, which is the same as string B.

Input: A = “aaa”, B = “bbb”, arr[] = {0}
Output : No

Approach: Follow the below steps to solve the problem:



  • If the length of both the strings are not equal, then string A can’t be transformed to string B. Therefore, print “No”.
  • Traverse the given array arr[] and check if characters at A[arr[i]] and B[arr[i]] are same or not. If found to be true, then print “No”. Otherwise, perform the following steps:
    • If the first element of arr[i] is not 0:
    • Similarly, if the last element of arr[i] is not equal to the element at index (N – 1), then:
    • Iterate a loop from 1 to N and initialize two pointers, L = arr[i – 1] and R = arr[i]:

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to count frequency of the
// characters of two given strings
bool isEqual(string& A, string& B)
{
    // Stores the frequencies of
    // characters of strings A and B
    map<char, int> mp, mp1;
 
    // Traverse the string A
    for (auto it : A) {
 
        // Update frequency of
        // each character
        mp[it]++;
    }
 
    // Traverse the string B
    for (auto it : B) {
 
        // Update frequency of
        // each character
        mp1[it]++;
    }
 
    // Traverse the Map
    for (auto it : mp) {
 
        // If the frequency a character
        // is not the same in both the strings
        if (it.second != mp1[it.first]) {
            return false;
        }
    }
 
    return true;
}
 
// Function to check if it is possible
// to convert string A to string B
void IsPossible(string& A, string& B,
                int arr[], int N)
{
 
    // Base Case
    if (A == B) {
        cout << "Yes" << endl;
        return;
    }
 
    // If length of both the
    // strings are not equal
    if (A.length() != B.length()) {
        cout << "No" << endl;
        return;
    }
 
    // Traverse the array and check
    // if the blocked indices
    // contains the same character
    for (int i = 0; i < N; i++) {
        int idx = arr[i];
 
        // If there is a different
        // character, return No
        if (A[idx] != B[idx]) {
            cout << "No" << endl;
            return;
        }
    }
 
    // If the first index is not present
    if (arr[0]) {
        string X = "";
        string Y = "";
 
        // Extract characters from
        // string A and B
        for (int i = 0; i < arr[0]; i++) {
            X += A[i];
            Y += B[i];
        }
 
        // If frequency is not same
        if (!isEqual(A, B)) {
 
            cout << "No" << endl;
            return;
        }
    }
 
    // If last index is not present
    if (arr[N - 1] != (A.length() - 1)) {
        string X = "";
        string Y = "";
 
        // Extract characters from
        // string A and B
        for (int i = arr[N - 1] + 1;
             i < A.length(); i++) {
            X += A[i];
            Y += B[i];
        }
 
        // If frequency is not same
        if (!isEqual(A, B)) {
            cout << "No" << endl;
            return;
        }
    }
 
    // Traverse the array arr[]
    for (int i = 1; i < N; i++) {
 
        int L = arr[i - 1];
        int R = arr[i];
 
        string X = "";
        string Y = "";
 
        // Extract characters from strings A and B
        for (int j = L + 1; j < R; j++) {
            X += A[j];
            Y += B[j];
        }
 
        // If frequency is not same
        if (!isEqual(A, B)) {
            cout << "No" << endl;
            return;
        }
    }
 
    // If all conditions are satisfied
    cout << "Yes" << endl;
}
 
// Driver Code
int main()
{
    string A = "abcabka";
    string B = "acbakba";
    int arr[] = { 0, 3, 6 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    IsPossible(A, B, arr, N);
 
    return 0;
}

Python3




# Python3 program for the above approach
from collections import defaultdict
 
# Function to count frequency of the
# characters of two given strings
def isEqual(A, B):
     
    # Stores the frequencies of
    # characters of strings A and B
    mp = defaultdict(int)
    mp1 = defaultdict(int)
 
    # Traverse the string A
    for it in A:
 
        # Update frequency of
        # each character
        mp[it] += 1
 
    # Traverse the string B
    for it in B:
 
        # Update frequency of
        # each character
        mp1[it] += 1
 
    # Traverse the Map
    for it in mp:
 
        # If the frequency a character
        # is not the same in both the strings
        if (mp[it] != mp1[it]):
            return False
 
    return True
 
# Function to check if it is possible
# to convert string A to string B
def IsPossible(A, B, arr, N):
 
    # Base Case
    if (A == B):
        print("Yes")
        return
 
    # If length of both the
    # strings are not equal
    if (len(A) != len(B)):
        print("No")
        return
 
    # Traverse the array and check
    # if the blocked indices
    # contains the same character
    for i in range(N):
        idx = arr[i]
 
        # If there is a different
        # character, return No
        if (A[idx] != B[idx]):
            print("No")
            return
 
    # If the first index is not present
    if (arr[0]):
        X = ""
        Y = ""
 
        # Extract characters from
        # string A and B
        for i in range(arr[0]):
            X += A[i]
            Y += B[i]
 
        # If frequency is not same
        if (not isEqual(A, B)):
            print("No")
            return
 
    # If last index is not present
    if (arr[N - 1] != (len(A) - 1)):
        X = ""
        Y = ""
 
        # Extract characters from
        # string A and B
        for i in range(arr[N - 1] + 1,
                       len(A)):
            X += A[i]
            Y += B[i]
 
        # If frequency is not same
        if (not isEqual(A, B)):
            print("No")
            return
 
    # Traverse the array arr[]
    for i in range(1, N):
        L = arr[i - 1]
        R = arr[i]
 
        X = ""
        Y = ""
 
        # Extract characters from strings A and B
        for j in range(L + 1, R):
            X += A[j]
            Y += B[j]
 
        # If frequency is not same
        if (not isEqual(A, B)):
            print("No")
            return
 
    # If all conditions are satisfied
    print("Yes")
 
# Driver Code
if __name__ == "__main__":
 
    A = "abcabka"
    B = "acbakba"
    arr = [ 0, 3, 6 ]
    N = len(arr)
 
    IsPossible(A, B, arr, N)
 
# This code is contributed by ukasp
Output: 
Yes

 

Time Complexity: O(N)
Auxiliary Space: O(N)

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.

My Personal Notes arrow_drop_up
Recommended Articles
Page :