String conversion by swapping adjacent characters
Last Updated :
03 May, 2023
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");
}
Time Complexity: O(N*Log(N)) As We have sort the array due to which it N*Log(N)
Auxiliary Space: O(1)
Similar Reads
Make all Strings palindrome by swapping characters from adjacent Strings Given an array of strings S[] of size X where each string has length N. In one move, you can swap the ith character of two adjacent strings, the task is to find the minimum number of moves to make every string a palindrome. If this is not possible, print -1. Examples: Input: S[] = {"13", "21", "32"}
10 min read
Swapping Characters of a String in Java As we know that Object of String in Java are immutable (i.e. we cannot perform any changes once its created). To do modifications on string stored in a String object, we copy it to a character array, StringBuffer, etc and do modifications on the copy object.In this article we would go through some m
3 min read
Swap characters in a String Given a String S of length N, two integers B and C, the task is to traverse characters starting from the beginning, swapping a character with the character after C places from it, i.e. swap characters at position i and (i + C)%N. Repeat this process B times, advancing one position at a time. Your ta
14 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
String character swap problem Given a string S of length N consisting of characters 'L' (sees every character lying to its left) or 'R' (sees every character lying to its right). In one operation, any two consecutive characters can be swapped. The operation can be performed at most once. Determine whether or not each character i
6 min read