Open In App

Check if string A can be converted to string B by changing A[i] to A[i+1] or A[i]..A[i+K-1] to A[i]+1 each

Improve
Improve
Like Article
Like
Save
Share
Report

Given two strings A and B each of length N and an integer K, the task is to find if string A can be converted to string B, using the following operations any number of times:

  • Type1: Choose index i, and swap Ai and Ai+1
  • Type2: Choose index i, and if Ai, Ai+1, …, Ai+K-1 are all equal to some character ch ( ch ≠ z ), replace each character with its next character (ch+1), for ex: ‘d’ is replaced by ‘e’ and so on.

Examples:

Input: N = 4, A = “abba”, B = “azza”, K = 2 
Output: Yes
Explanation: Using second operation, we can convert the same characters to their next character,  
and thus get the required string B.
“abba” -> “acca” -> “adda” -> . . . -> “azza”

Input: N = 2, A = “zz”, B = “aa”, K = 1
Output: No

 

Approach: Observing the operation of type1, it is obvious that after some finite sequence of swaps, the string can be reordered in any way. So there is no need to worry about the characters being adjacent during the operation of the second type (as reordering of strings can be done anytime), so only the frequency of characters matters. Following are the steps to be followed:

  • So, to convert string A to string B, there is need to make frequencies of each character of the alphabet equal, then reorder the string using the operation of first type.
  • If for any character i, any insufficient number of occurrences (frequency i, A < frequency i, B ) or if remaining occurrences of character which cannot be converted into the next character (frequency i, A – frequency i, B) is not a multiple of K (as to convert character to its next character length greater than K is needed), then the answer would be NO otherwise YES.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
void solve(string& A, string& B, int& N,
           int& K)
{
    // Initializing two vectors to count
    // frequency of two strings
    int arr1[26] = { 0 }, arr2[26] = { 0 };
    bool flag = true;
    for (int i = 0; i < N; i++) {
        arr1[A[i] - 'a']++;
        arr2[B[i] - 'a']++;
    }
    int count = 0;
    for (int i = 0; i < 26 && flag; i++) {
 
        // Till 'y' is not encountered,
        // say ch would be changed to ch+1
        arr1[i] += count;
 
        // Doing required operation to check
        // if frequencies of each character
        // of alphabet is atleast equal
        if (arr1[i] >= arr2[i]) {
 
            // Checking for case when
            // remaining occurrences cannot be
            // converted to next character
            if ((arr1[i] - arr2[i]) % K) {
                flag = false;
            }
            // Here, the characters from
            // string A which were needed
            // for string B are taken in count
            count = arr1[i] - arr2[i];
            continue;
        }
        else {
            flag = false;
        }
    }
    if (flag) {
        cout << "Yes"
             << "\n";
    }
    else {
        cout << "No"
             << "\n";
    }
}
 
// Driver Code
int main()
{
    string A = "zz", B = "aa";
    int N = A.size();
    int K = 1;
    solve(A, B, N, K);
    return 0;
}


Java




// Java program for the above approach
class GFG {
 
  static void solve(String A, String B, int N, int K)
  {
 
    // Initializing two vectors to count
    // frequency of two Strings
    int[] arr1 = new int[26];
    int[] arr2 = new int[26];
    for (int i = 0; i < 26; i++) {
      arr1[i] = 0;
      arr2[i] = 0;
    }
 
    boolean flag = true;
    for (int i = 0; i < N; i++) {
      arr1[A.charAt(i) - 'a']++;
      arr2[B.charAt(i) - 'a']++;
    }
    int count = 0;
    for (int i = 0; i < 26 && flag; i++) {
 
      // Till 'y' is not encountered,
      // say ch would be changed to ch+1
      arr1[i] += count;
 
      // Doing required operation to check
      // if frequencies of each character
      // of alphabet is atleast equal
      if (arr1[i] >= arr2[i]) {
 
        // Checking for case when
        // remaining occurences cannot be
        // converted to next character
        if ((arr1[i] - arr2[i]) % K == 1) {
          flag = false;
        }
        // Here, the characters from
        // String A which were needed
        // for String B are taken in count
        count = arr1[i] - arr2[i];
        continue;
      }
      else {
        flag = false;
      }
    }
    if (flag) {
      System.out.println("Yes");
    }
    else {
      System.out.println("No");
    }
  }
 
  // Driver Code
  public static void main(String args[])
  {
    String A = "zz", B = "aa";
    int N = A.length();
    int K = 1;
    solve(A, B, N, K);
  }
}
 
// This code is contributed by Saurabh Jaiswal


Python3




# Python code for the above approach
def solve(A, B, N, K):
 
    # Initializing two vectors to count
    # frequency of two strings
    arr1 = [0] * 26
    arr2 = [0] * 26
    flag = True;
    for i in range(N):
        arr1[ord(A[i]) - ord('a')] += 1
        arr2[ord(B[i]) - ord('a')] += 1
     
    count = 0;
    for i in range(26):
        if(flag):
           
            # Till 'y' is not encountered,
            # say ch would be changed to ch+1
            arr1[i] += count;
 
            # Doing required operation to check
            # if frequencies of each character
            # of alphabet is atleast equal
            if (arr1[i] >= arr2[i]):
 
                # Checking for case when
                # remaining occurences cannot be
                # converted to next character
                if ((arr1[i] - arr2[i]) % K):
                    flag = False;
                 
                # Here, the characters from
                # string A which were needed
                # for string B are taken in count
                count = arr1[i] - arr2[i];
                continue;
         
            else:
                flag = False;
         
    if (flag):
        print("Yes")
    else:
        print("No")
     
# Driver Code
A = "zz"
B = "aa";
N = len(A)
K = 1;
solve(A, B, N, K);
 
# This code is contributed by gfgking


C#




// C# program for the above approach
using System;
class GFG {
 
  static void solve(string A, string B, int N, int K)
  {
    // Initializing two vectors to count
    // frequency of two strings
    int[] arr1 = new int[26];
    int[] arr2 = new int[26];
    for (int i = 0; i < 26; i++) {
      arr1[i] = 0;
      arr2[i] = 0;
    }
 
    bool flag = true;
    for (int i = 0; i < N; i++) {
      arr1[A[i] - 'a']++;
      arr2[B[i] - 'a']++;
    }
    int count = 0;
    for (int i = 0; i < 26 && flag; i++) {
 
      // Till 'y' is not encountered,
      // say ch would be changed to ch+1
      arr1[i] += count;
 
      // Doing required operation to check
      // if frequencies of each character
      // of alphabet is atleast equal
      if (arr1[i] >= arr2[i]) {
 
        // Checking for case when
        // remaining occurences cannot be
        // converted to next character
        if ((arr1[i] - arr2[i]) % K == 1) {
          flag = false;
        }
        // Here, the characters from
        // string A which were needed
        // for string B are taken in count
        count = arr1[i] - arr2[i];
        continue;
      }
      else {
        flag = false;
      }
    }
    if (flag) {
      Console.WriteLine("Yes");
    }
    else {
      Console.WriteLine("No");
    }
  }
 
  // Driver Code
  public static void Main()
  {
    string A = "zz", B = "aa";
    int N = A.Length;
    int K = 1;
    solve(A, B, N, K);
  }
}
 
// This code is contributed by Samim Hossain Mondal.


Javascript




<script>
       // JavaScript code for the above approach
       function solve(A, B, N, K)
       {
        
           // Initializing two vectors to count
           // frequency of two strings
           let arr1 = new Array(26).fill(0);
           let arr2 = new Array(26).fill(0);
           let flag = true;
           for (let i = 0; i < N; i++) {
               arr1[A[i].charCodeAt(0) - 'a'.charCodeAt(0)]++;
               arr2[B[i].charCodeAt(0) - 'a'.charCodeAt(0)]++;
           }
           let count = 0;
           for (let i = 0; i < 26 && flag; i++) {
 
               // Till 'y' is not encountered,
               // say ch would be changed to ch+1
               arr1[i] += count;
 
               // Doing required operation to check
               // if frequencies of each character
               // of alphabet is atleast equal
               if (arr1[i] >= arr2[i]) {
 
                   // Checking for case when
                   // remaining occurences cannot be
                   // converted to next character
                   if ((arr1[i] - arr2[i]) % K) {
                       flag = false;
                   }
                    
                   // Here, the characters from
                   // string A which were needed
                   // for string B are taken in count
                   count = arr1[i] - arr2[i];
                   continue;
               }
               else {
                   flag = false;
               }
           }
           if (flag) {
               document.write("Yes" + "<br>")
           }
           else {
               document.write("No" + "<br>")
           }
       }
 
       // Driver Code
       let A = "zz", B = "aa";
       let N = A.length;
       let K = 1;
       solve(A, B, N, K);
 
      // This code is contributed by Potta Lokesh
   </script>


 
 

Output

No

 

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

 



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