Minimum adjacent swaps to group similar characters together
Last Updated :
16 Jul, 2021
Given a string S of length N, consisting of only lowercase English characters, the task is to find the minimum number of adjacent swaps required to group the same characters together.
Examples:
Input: S = “cbabc”
Output: 4
Explanation:
Swap characters S[0] to S[1]. Therefore, S = “bcabc”.
Swap characters S[1] to S[2]. Therefore, S = “bacbc”.
Swap characters S[2] to S[3]. Therefore, S = “babcc”.
Swap characters S[1] to S[2]. Therefore, S = “bbacc”.
Hence, the total swaps required is 4.
Input: S = “abcd”
Output: 0
Explanation:
All characters are distinct. Hence, no swapping is required.
Approach: The idea is to store the indices of each character. Then, for each character, find the adjacent absolute differences and add them to the answer. Follow the steps below to solve the problem:
- Initialize a 2D vector arr[], where vector arr[i] will store the indices of character (i + ‘a’) and a variable answer initialized to 0.
- Iterate the given string over the range [0, N – 1].
- Add index i to arr[S[i] – ‘a’].
- After traversing the string, traverse the 2D vector arr[] from i = ‘a’ to ‘z’.
- For each character i, find the absolute adjacent differences of the indices of character i present in that vector and add them to the answer.
- After traversing the 2D vector, print the answer as the minimum number of swaps.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int minSwaps(string S, int n)
{
int swaps = 0;
vector<vector< int > > arr(26);
for ( int i = 0; i < n; i++) {
int pos = S[i] - 'a' ;
arr[pos].push_back(i);
}
for ( char ch = 'a' ; ch <= 'z' ; ++ch) {
int pos = ch - 'a' ;
for ( int i = 1;
i < arr[pos].size(); ++i) {
swaps += abs (arr[pos][i]
- arr[pos][i - 1] - 1);
}
}
return swaps;
}
int main()
{
string S = "abbccabbcc" ;
int N = S.length();
cout << minSwaps(S, N);
return 0;
}
|
Java
import java.util.*;
class GFG{
static int minSwaps(String S, int n)
{
int swaps = 0 ;
@SuppressWarnings ( "unchecked" )
Vector<Integer> []arr = new Vector[ 26 ];
for ( int i = 0 ; i < arr.length; i++)
arr[i] = new Vector<Integer>();
for ( int i = 0 ; i < n; i++)
{
int pos = S.charAt(i) - 'a' ;
arr[pos].add(i);
}
for ( char ch = 'a' ; ch <= 'z' ; ++ch)
{
int pos = ch - 'a' ;
for ( int i = 1 ; i < arr[pos].size(); ++i)
{
swaps += Math.abs(arr[pos].get(i) -
arr[pos].get(i - 1 ) - 1 );
}
}
return swaps;
}
public static void main(String[] args)
{
String S = "abbccabbcc" ;
int N = S.length();
System.out.print(minSwaps(S, N));
}
}
|
Python3
def minSwaps(S, n):
swaps = 0
arr = [[] for i in range ( 26 )]
for i in range (n):
pos = ord (S[i]) - ord ( 'a' )
arr[pos].append(i)
for ch in range ( ord ( 'a' ), ord ( 'z' ) + 1 ):
pos = ch - ord ( 'a' )
for i in range ( 1 , len (arr[pos])):
swaps + = abs (arr[pos][i] -
arr[pos][i - 1 ] - 1 )
return swaps
if __name__ = = '__main__' :
S = "abbccabbcc"
N = len (S)
print (minSwaps(S, N))
|
C#
using System;
using System.Collections.Generic;
class GFG{
static int minSwaps(String S,
int n)
{
int swaps = 0;
List< int > []arr =
new List< int >[26];
for ( int i = 0;
i < arr.Length; i++)
arr[i] = new List< int >();
for ( int i = 0; i < n; i++)
{
int pos = S[i] - 'a' ;
arr[pos].Add(i);
}
for ( char ch = 'a' ;
ch <= 'z' ; ++ch)
{
int pos = ch - 'a' ;
for ( int i = 1;
i < arr[pos].Count; ++i)
{
swaps += Math.Abs(arr[pos][i] -
arr[pos][i - 1] - 1);
}
}
return swaps;
}
public static void Main(String[] args)
{
String S = "abbccabbcc" ;
int N = S.Length;
Console.Write(minSwaps(S, N));
}
}
|
Javascript
<script>
function minSwaps(S,n)
{
let swaps = 0;
let arr = new Array(26);
for (let i = 0; i < arr.length; i++)
arr[i] = [];
for (let i = 0; i < n; i++)
{
let pos = S[i].charCodeAt(0) - 'a' .charCodeAt(0);
arr[pos].push(i);
}
for (let ch = 'a' .charCodeAt(0); ch <= 'z' .charCodeAt(0); ++ch)
{
let pos = ch - 'a' .charCodeAt(0);
for (let i = 1; i < arr[pos].length; ++i)
{
swaps += Math.abs(arr[pos][i] -
arr[pos][i-1] - 1);
}
}
return swaps;
}
let S = "abbccabbcc" ;
let N = S.length;
document.write(minSwaps(S, N));
</script>
|
Time Complexity: O(26*N)
Auxiliary Space: O(N)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...