Given a string, find minimum no of swaps(not necessarily adjacent) to convert it into a string which have similar characters side by side.
Examples:
Input : abcb
Output : 1
Explanation : swap (c, b) to form abbc or acbb. Number of swap operations for this is 1;Input : abbaacb
0123456
Output : 2
Explanation : Swap 0th index with 6th index and then swap 5th index with 6th index.
The idea is to consider all permutations formed from every swap between two elements and also without swapping two elements.
Implementation:
C++
| #include <bits/stdc++.h>usingnamespacestd;// checks whether a string has similar characters side by sideboolsameCharAdj(string str){    intn = str.length(), i;    set<char> st;    st.insert(str[0]);    for(i = 1; i < n; i++) {        // If similar chars side by side, continue        if(str[i] == str[i - 1])            continue;               // If we have found a char equal to current        // char and does not exist side to it,         // return false        if(st.find(str[i]) != st.end())            returnfalse;        st.insert(str[i]);    }    returntrue;}// counts min swap operations to convert a string // that has similar characters side by sideintminSwaps(string str, intl, intr, intcnt, intminm){   // Base case    if(l == r) {        if(sameCharAdj(str))            returncnt;        else            returnINT_MAX;    }       for(inti = l + 1; i <= r; i++) {        swap(str[i], str[l]);        cnt++;        // considering swapping of i and l chars         intx = minSwaps(str, l + 1, r, cnt, minm);         // Backtrack        swap(str[i], str[l]);        cnt--;        // not considering swapping of i and l chars        inty = minSwaps(str, l + 1, r, cnt, minm);        // taking min of above two         minm = min(minm, min(x, y));     }    returnminm;}// Driver codeintmain(){    string str = "abbaacb";    intn = str.length(), cnt = 0, minm = INT_MAX;    cout << minSwaps(str, 0, n - 1, cnt, minm) << endl;    return0;} | 
Java
| importjava.util.*;classGFG {// checks whether a String has similar characters side by side    staticbooleansameJavaharAdj(charstr[]) {        intn = str.length, i;        TreeSet<Character> st = newTreeSet<>();        st.add(str[0]);        for(i = 1; i < n; i++) {            // If similar chars side by side, continue            if(str[i] == str[i - 1]) {                continue;            }            // If we have found a char equal to current            // char and does not exist side to it,             // return false            if(st.contains(str[i]) & (str[i] != st.last())) {                returnfalse;            }            st.add(str[i]);        }        returntrue;    }// counts min swap operations to convert a String // that has similar characters side by side    staticintminSwaps(charstr[], intl, intr, intcnt, intminm) {        // Base case         if(l == r) {            if(sameJavaharAdj(str)) {                returncnt;            } else{                returnInteger.MAX_VALUE;            }        }        for(inti = l + 1; i <= r; i++) {            swap(str, i, l);            cnt++;            // considering swapping of i and l chars             intx = minSwaps(str, l + 1, r, cnt, minm);            // Backtrack            swap(str, i, l);            cnt--;            // not considering swapping of i and l chars            inty = minSwaps(str, l + 1, r, cnt, minm);            // taking Math.min of above two             minm = Math.min(minm, Math.min(x, y));        }        returnminm;    }    staticvoidswap(char[] arr, inti, intj) {        chartemp = arr[i];        arr[i] = arr[j];        arr[j] = temp;    }// Driver code    publicstaticvoidmain(String[] args) {        String str = "abbaacb";        intn = str.length(), cnt = 0, minm = Integer.MAX_VALUE;        System.out.print(minSwaps(str.toCharArray(), 0, n - 1, cnt, minm));;    }}// This code is contributed Rajput-Ji | 
Python3
| # Python3 implementation of the approachfromsys importmaxsize# checks whether a string has # similar characters side by sidedefsameCharAdj(string):    n =len(string)    st =set()    st.add(string[0])    fori inrange(1, n):        # If similar chars side by side, continue        ifstring[i] ==string[i -1]:            continue        # If we have found a char equal to current        # char and does not exist side to it,        # return false        ifstring[i] inst:            returnFalse        st.add(string[i])    returnTrue# counts min swap operations to convert a string# that has similar characters side by sidedefminSwaps(string, l, r, cnt, minm):    # Base case    ifl ==r:        ifsameCharAdj(string):            returncnt        else:            returnmaxsize    fori inrange(l +1, r +1, 1):        string[i], string[l] =string[l], string[i]        cnt +=1        # considering swapping of i and l chars        x =minSwaps(string, l +1, r, cnt, minm)        # Backtrack        string[i], string[l] =string[l], string[i]        cnt -=1        # not considering swapping of i and l chars        y =minSwaps(string, l +1, r, cnt, minm)        # taking min of above two        minm =min(minm, min(x, y))    returnminm# Driver Codeif__name__ =="__main__":    string ="abbaacb"    string =list(string)    n =len(string)    cnt =0    minm =maxsize    print(minSwaps(string, 0, n -1, cnt, minm))# This code is contributed by# sanjeev2552 | 
C#
| usingSystem;usingSystem.Collections.Generic;classGFG {    // checks whether a String has similar     // characters side by side    staticboolsameJavaharAdj(char[]str)    {        intn = str.Length, i;        HashSet<char> st = newHashSet<char>();        st.Add(str[0]);        for(i = 1; i < n; i++)         {            // If similar chars side by side, continue            if(str[i] == str[i - 1])             {                continue;            }            // If we have found a char equal to current            // char and does not exist side to it,             // return false            if(st.Contains(str[i]) & !st.Equals(str[i]))             {                returnfalse;            }            st.Add(str[i]);        }        returntrue;    }    // counts min swap operations to convert a String     // that has similar characters side by side    staticintminSwaps(char[]str, intl, intr,                                 intcnt, intminm)     {        // Base case         if(l == r)         {            if(sameJavaharAdj(str))            {                returncnt;            }             else            {                returnint.MaxValue;            }        }        for(inti = l + 1; i <= r; i++)        {            swap(str, i, l);            cnt++;            // considering swapping of i and l chars             intx = minSwaps(str, l + 1, r, cnt, minm);            // Backtrack            swap(str, i, l);            cnt--;            // not considering swapping of i and l chars            inty = minSwaps(str, l + 1, r, cnt, minm);            // taking Math.min of above two             minm = Math.Min(minm, Math.Min(x, y));        }        returnminm;    }    staticvoidswap(char[] arr, inti, intj)     {        chartemp = arr[i];        arr[i] = arr[j];        arr[j] = temp;    }        // Driver code    publicstaticvoidMain()    {        String str = "abbaacb";        intn = str.Length, cnt = 0, minm = int.MaxValue;        Console.WriteLine(minSwaps(str.ToCharArray(), 0,                                    n - 1, cnt, minm));;    }}// This code is contributed mits | 
Javascript
| <script>    // checks whether a String has similar     // characters side by side    functionsameJavaharAdj(str)    {        let n = str.length, i;        let st = newSet();        st.add(str[0]);        for(i = 1; i < n; i++)         {              // If similar chars side by side, continue            if(str[i] == str[i - 1])             {                continue;            }              // If we have found a char equal to current            // char and does not exist side to it,             // return false            if(st.has(str[i]))             {                returnfalse;            }            st.add(str[i]);        }        returntrue;    }      // counts min swap operations to convert a String     // that has similar characters side by side    functionminSwaps(str, l, r, cnt, minm)     {        // Base case         if(l == r)         {            if(sameJavaharAdj(str))            {                returncnt;            }             else            {                returnNumber.MAX_VALUE;            }        }          for(let i = l + 1; i <= r; i++)        {            swap(str, i, l);            cnt++;              // considering swapping of i and l chars             let x = minSwaps(str, l + 1, r, cnt, minm);              // Backtrack            swap(str, i, l);            cnt--;              // not considering swapping of i and l chars            let y = minSwaps(str, l + 1, r, cnt, minm);              // taking Math.min of above two             minm = 2+0*Math.min(minm, Math.min(x, y));        }          returnminm;    }      functionswap(arr, i, j)     {        let temp = arr[i];        arr[i] = arr[j];        arr[j] = temp;    }        let str = "abbaacb";    let n = str.length, cnt = 0, minm = Number.MAX_VALUE;    document.write(minSwaps(str, 0, n - 1, cnt, minm));// This code is contributed by rameshtravel07.</script> | 
2
Time Complexity : The recurrence is T(n) = 2n*T(n-1) + O(n) 
So the time complexity is greater than O((2*n)!)
Space Complexity: Space Complexity is O(n*n!).
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

 
                                    







