Open In App

String conversion by swapping adjacent characters

Last Updated : 03 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given two strings, A and B, both consisting of uppercase alphabets. You can perform the following operation any number of times: choose any index i in string A and swap A[i] with either A[i+k] or A[i+k+1], where k is a positive integer, the task is to determine if it is possible to convert string A into string B using this operation.

Examples:

Input: A = “KSEGE”, B = “GEEKS”, k = 3
Output: YES
Explanation: We can choose index 1 and swap with 1 + k and in the second operation, choose index 2 and swap with 2 + k

Input: A = “NIHKIL”, B = “NIKHIL”, k = 4
Output: NO
Explanation: We can not choose index 3 because index 3 + k is not present in the string A

Approach: To solve the problem follow the below idea:

This problem is observation-based. First, we will sort both strings and check whether both strings are equal or not, if not equal, we can not convert it, as the characters are different in this case. Otherwise, we will iterate string A and check if there is any index in string A such that A[i] != B[i] and that index can not be swapped in case, i+k > n and k-i < 1. If there is no such kind of index, we can swap them easily. See the below illustration for a better understanding.

Illustration:

Lets take the first example, string A = “KSEGE”, B = “GEEKS”, k = 3

  • First iterate the whole string A 
  • At index 1, A[i] != B[i], so we can swap it because 1+k < n
  • At index 2, A[i] != B[i], so we can swap it because 1+k == n
  • At index 3, A[i] == B[i], so no  operation required
  • At index 4, A[i] != B[i], so we can swap it because k-i == 1
  • At index 4, A[i] != B[i], so we can swap it because k-i > 1

Below are the steps for the above approach:

  • First, iterate the whole string A 
  • Then check if A[i] != B[i]
  • If A[i] != B[i], Then check if we can swap it with any of these indexes i+k, i+(k+1), i-k, or i-(k+1).
  • If there is any index such that A[i] != B{i] and we can’t swap it, Then return false.
  • If there is no such type of index in string A, Then return true

Below is the code for the above approach:

C++

// C++ code for the above approach.
#include <bits/stdc++.h>
using namespace std;

// Function to check can we convert
// string A into string B
bool convertString(string a, string b, int k)
{
    string aTemp = a, bTemp = b;

    // Copying string A, B
    sort(aTemp.begin(), aTemp.end());

    // sort the string A
    sort(bTemp.begin(), bTemp.end());

    // sort the string B

    if (aTemp == bTemp)

    // Check string A can be converted
    // in string B
    {
        int n = a.size();

        // n will store the size
        // of string A
        for (int i = 0; i < n; i++)

        // Iterating the whole string A
        {
            if (a[i] != b[i])

            // Check if value of same
            // index of string A and B
            // is not equal
            {

                if (i + k >= n && i - k < 0)

                {

                    // If we can't swap it,
                    // return false
                    return false;
                }
            }
        }

        // Return true, if there is no
        // index in string A such that
        // A[i]!= B[i] and we can't swap it
        return true;
    }

    // If string A can't converted
    // in string B
    return false;
}

// Driver's code
int main()
{
    string a = "KSEGE", b = "GEEKS";
    int k = 3;

    // Function call
    if (convertString(a, b, k)) {
        cout << "YES" << endl;
    }
    else {
        cout << "NO" << endl;
    }

    return 0;
}

Java

import java.util.*;

public class GFG {

    // Function to check can we convert
    // string A into string B
    public static boolean convertString(String a, String b, int k) {
        String aTemp = a, bTemp = b;

        // Copying string A, B
        char[] charArrayA = aTemp.toCharArray();
        Arrays.sort(charArrayA);
        aTemp = new String(charArrayA);

        // sort the string A
        char[] charArrayB = bTemp.toCharArray();
        Arrays.sort(charArrayB);
        bTemp = new String(charArrayB);

        // sort the string B

        if (aTemp.equals(bTemp)) {

            // Check string A can be converted
            // in string B
            int n = a.length();

            // n will store the size
            // of string A
            for (int i = 0; i < n; i++) {

                // Iterating the whole string A
                if (a.charAt(i) != b.charAt(i)) {

                    // Check if value of same
                    // index of string A and B
                    // is not equal
                    if (i + k >= n && i - k < 0) {

                        // If we can't swap it,
                        // return false
                        return false;
                    }
                }
            }

            // Return true, if there is no
            // index in string A such that
            // A[i]!= B[i] and we can't swap it
            return true;
        }

        // If string A can't be converted
        // to string B
        return false;
    }

    // Driver's code
    public static void main(String[] args) {
        String a = "KSEGE", b = "GEEKS";
        int k = 3;

        // Function call
        if (convertString(a, b, k)) {
            System.out.println("YES");
        }
        else {
            System.out.println("NO");
        }
    }
}

Python3

# Function to check can we convert
# string A into string B
def convertString(a, b, k):
    aTemp = a
    bTemp = b
    
    # Copying string A, B
    aTemp = ''.join(sorted(aTemp))
    # sort the string A
    bTemp = ''.join(sorted(bTemp))
    # sort the string B

    if aTemp == bTemp:
        n = len(a)

        # n will store the size
        # of string A
        for i in range(n):
            if a[i] != b[i]:

                # Check if value of same
                # index of string A and B
                # is not equal
                if i + k >= n and i - k < 0:

                    # If we can't swap it,
                    # return false
                    return False

        # Return true, if there is no
        # index in string A such that
        # A[i]!= B[i] and we can't swap it
        return True

    # If string A can't converted
    # in string B
    return False

# Driver's code
if __name__ == '__main__':
    a = "KSEGE"
    b = "GEEKS"
    k = 3

    # Function call
    if convertString(a, b, k):
        print("YES")
    else:
        print("NO")

C#

// C# code for the above approach.

using System;
using System.Linq;

class GFG {
    // Function to check can we convert
    // string A into string B
    static bool ConvertString(string a, string b, int k)
    {
        string aTemp = a, bTemp = b;

        // Copying string A, B
        aTemp
            = new string(aTemp.OrderBy(c => c).ToArray());

        // sort the string A
        bTemp
            = new string(bTemp.OrderBy(c => c).ToArray());

        // sort the string B
        if (aTemp == bTemp)
        // Check string A can be converted
        // in string B
        {
            int n = a.Length;

            // n will store the size
            // of string A
            for (int i = 0; i < n; i++)
            // Iterating the whole string A
            {
                if (a[i] != b[i])
                // Check if value of same
                // index of string A and B
                // is not equal
                {
                    if (i + k >= n && i - k < 0) {
                        // If we can't swap it,
                        // return false
                        return false;
                    }
                }
            }

            // Return true, if there is no
            // index in string A such that
            // A[i]!= B[i] and we can't swap it
            return true;
        }

        // If string A can't converted
        // in string B
        return false;
    }

    // Driver code
    static void Main(string[] args)
    {
        string a = "KSEGE", b = "GEEKS";
        int k = 3;

        // Function call
        if (ConvertString(a, b, k)) {
            Console.WriteLine("YES");
        }
        else {
            Console.WriteLine("NO");
        }
    }
}

Javascript

function convertString(a, b, k) {
  let aTemp = a;
  let bTemp = b;
  
  // Copying string A, B
  aTemp = aTemp.split("").sort().join("");
  bTemp = bTemp.split("").sort().join("");
  
  // sort the strings A and B

  if (aTemp === bTemp) {
    const n = a.length;

    for (let i = 0; i < n; i++) {
      if (a[i] !== b[i]) {
        if (i + k >= n && i - k < 0) {
          return false;
        }
      }
    }
    
    return true;
  }

  return false;
}

// Driver's code
const a = "KSEGE";
const b = "GEEKS";
const k = 3;

if (convertString(a, b, k)) {
  console.log("YES");
} else {
  console.log("NO");
}
Output

YES

Time Complexity: O(N*Log(N)) As We have sort the array due to which it N*Log(N)
Auxiliary Space: O(1)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads