Given a string S consisting of N characters, the task is to find the minimum number of pairs of characters that are required to be swapped such that no two adjacent characters are the same. If it is not possible to do so, then print “-1”.
Examples:
Input: S = “ABAACD”
Output: 1
Explanation: Swapping S[3] and S[4] modifies the given string S to “ABACAD”. Since no two adjacent characters are the same, the minimum number of operations required is 1.
Input: S = “AABA”
Output: -1
Approach: The given problem can be solved by using Backtracking. The idea is to generate all possible combinations of swapping of a pair of indices and then if the string is generated having no adjacent characters same with minimum swap, then print that minimum number of swaps operations performed. Follow the steps below to solve the problem:
- Define a function minimumSwaps(string &str, int &minimumSwaps, int swaps=0, int idx) and perform the following operations:
- If the adjacent characters of the string str are different then update the value of minimumSwaps to the minimum of minimumSwaps and swaps.
- Iterate over the range [idx, N] using the variable i and performing the following operations:
- Iterate over the range [i + 1, N] using the variable j and performing the following operations:
- Swap the characters at positions i and j in string S.
- Call for the function minimumSwaps(str, minimumSwaps, swaps+1, i + 1) to find other possible pairs of swapping to generate the resultant string.
- Swap the characters in positions i and j in the string S.
- Initialize the variable, say ansSwaps as INT_MAX to store the count of minimum swaps required.
- Call the function minimumSwaps(str, ansSwaps) to find the minimum number of swaps required to make all the adjacent characters different.
- After completing the above steps, if the value of ansSwaps is INT_MAX, then print -1. Otherwise, print the value of ansSwaps as the resultant minimum swaps.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool check(string& S)
{
for ( int i = 1; i < S.length(); i++) {
if (S[i - 1] == S[i]) {
return false ;
}
}
return true ;
}
void minimumSwaps(string& S, int & ansSwaps,
int swaps = 0, int idx = 0)
{
if (check(S)) {
ansSwaps = min(ansSwaps, swaps);
}
for ( int i = idx;
i < S.length(); i++) {
for ( int j = i + 1;
j < S.length(); j++) {
swap(S[i], S[j]);
minimumSwaps(S, ansSwaps,
swaps + 1, i + 1);
swap(S[i], S[j]);
}
}
}
void findMinimumSwaps(string& S)
{
int ansSwaps = INT_MAX;
minimumSwaps(S, ansSwaps);
if (ansSwaps == INT_MAX)
cout << "-1" ;
else
cout << ansSwaps;
}
int main()
{
string S = "ABAACD" ;
findMinimumSwaps(S);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int ansSwaps ;
static boolean check( char [] S)
{
for ( int i = 1 ; i < S.length; i++) {
if (S[i - 1 ] == S[i]) {
return false ;
}
}
return true ;
}
static void minimumSwaps( char [] S,
int swaps, int idx)
{
if (check(S)) {
ansSwaps = Math.min(ansSwaps, swaps);
}
for ( int i = idx;
i < S.length; i++) {
for ( int j = i + 1 ;
j < S.length; j++) {
swap(S,i,j);
minimumSwaps(S,
swaps + 1 , i + 1 );
S= swap(S,i,j);
}
}
}
static char [] swap( char []arr, int i, int j){
char temp= arr[i];
arr[i]=arr[j];
arr[j]=temp;
return arr;
}
static void findMinimumSwaps( char [] S)
{
ansSwaps = Integer.MAX_VALUE;
minimumSwaps(S, 0 , 0 );
if (ansSwaps == Integer.MAX_VALUE)
System.out.print( "-1" );
else
System.out.print(ansSwaps);
}
public static void main(String[] args)
{
String S = "ABAACD" ;
findMinimumSwaps(S.toCharArray());
}
}
|
Python3
import sys
ansSwaps = 0
def check(S):
for i in range ( 1 , len (S)):
if (S[i - 1 ] = = S[i]):
return False
return True
def minimumSwaps(S, swaps , idx):
global ansSwaps
if (check(S)):
ansSwaps = 1 + min (ansSwaps, swaps)
for i in range (idx, len (S)):
for j in range (i + 1 , len (S)):
swap(S, i, j)
minimumSwaps(S, swaps + 1 , i + 1 )
S = swap(S, i, j)
def swap(arr , i , j):
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
return arr
def findMinimumSwaps(S):
global ansSwaps
ansSwaps = sys.maxsize
minimumSwaps(S, 0 , 0 )
if (ansSwaps = = sys.maxsize):
print ( "-1" )
else :
print (ansSwaps)
S = "ABAACD"
findMinimumSwaps(S.split())
|
C#
using System;
public class GFG
{
static int ansSwaps ;
static bool check( char [] S)
{
for ( int i = 1; i < S.Length; i++) {
if (S[i - 1] == S[i]) {
return false ;
}
}
return true ;
}
static void minimumSwaps( char [] S,
int swaps, int idx)
{
if (check(S)) {
ansSwaps = Math.Min(ansSwaps, swaps);
}
for ( int i = idx;
i < S.Length; i++) {
for ( int j = i + 1;
j < S.Length; j++) {
swap(S,i,j);
minimumSwaps(S,
swaps + 1, i + 1);
S= swap(S,i,j);
}
}
}
static char [] swap( char []arr, int i, int j){
char temp= arr[i];
arr[i]=arr[j];
arr[j]=temp;
return arr;
}
static void findMinimumSwaps( char [] S)
{
ansSwaps = int .MaxValue;
minimumSwaps(S, 0,0);
if (ansSwaps == int .MaxValue)
Console.Write( "-1" );
else
Console.Write(ansSwaps);
}
public static void Main(String[] args)
{
String S = "ABAACD" ;
findMinimumSwaps(S.ToCharArray());
}
}
|
Javascript
<script>
var ansSwaps ;
function check(S)
{
for ( var i = 1; i < S.length; i++) {
if (S[i - 1] == S[i]) {
return false ;
}
}
return true ;
}
function minimumSwaps(S, swaps , idx)
{
if (check(S)) {
ansSwaps = Math.min(ansSwaps, swaps);
}
for ( var i = idx;
i < S.length; i++) {
for ( var j = i + 1;
j < S.length; j++) {
swap(S,i,j);
minimumSwaps(S,
swaps + 1, i + 1);
S= swap(S,i,j);
}
}
}
function swap(arr , i , j){
var temp= arr[i];
arr[i]=arr[j];
arr[j]=temp;
return arr;
}
function findMinimumSwaps(S)
{
ansSwaps = Number.MAX_VALUE;
minimumSwaps(S, 0,0);
if (ansSwaps == Number.MAX_VALUE)
document.write( "-1" );
else
document.write(ansSwaps);
}
var S = "ABAACD" ;
findMinimumSwaps(S.split( '' ));
</script>
|
Time Complexity: O(N3*2N)
Auxiliary Space: O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
07 Dec, 2021
Like Article
Save Article