Minimize Cost to sort a String in Increasing Order of Frequencies of Characters
Given a string S, the task is to calculate the minimum cost to sort the string in increasing order of their frequencies by swapping a block of repeated characters with another block of different repeated characters. The cost of each operation is the absolute difference of the two blocks.
Examples:
Input: S = “aabbcccdeffffggghhhhhii”
Output: 5
Explanation:
- Swap ‘d’ with ‘aa’. The Cost of this Operation is 1
- Swap ‘e’ with ‘bb’. The Cost of this Operation is 1
- Swap ‘ii’ with ‘ccc’. The Cost of this Operation is cost is 1
- Swap ‘ccc’ with ‘ffff’. The Cost of this Operation is 1
- Swap ‘ffff’ with ‘hhhhh’. The Cost of this Operation is 1
Input : S = “aaaa”
Output : 0
Approach:
Follow the steps below to solve the problem:
- Store the frequency of each character present in the String.
- Sort the frequencies.
- Calculate the difference between each frequency in the sorted and original sequence.
- Half of the total sum of all the differences is the required answer. This is because, for each swap, the difference is calculated twice in the above step.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int sortString(string S)
{
vector< int > sorted, original;
bool insert = false ;
if (S.length() == 1)
{
cout << 0 << endl;
}
int curr = 1;
for ( int i = 0; i < (S.length() - 1); i++)
{
if (S[i] == S[i + 1])
{
curr += 1;
insert = false ;
}
else
{
sorted.push_back(curr);
original.push_back(curr);
curr = 1;
insert = true ;
}
}
if ((S[(S.length() - 1)] !=
S[(S.length() - 2)]) || insert == false )
{
sorted.push_back(curr);
original.push_back(curr);
}
sort(sorted.begin(), sorted.end());
int t_cost = 0;
for ( int i = 0; i < sorted.size(); i++)
{
t_cost += abs (sorted[i] -
original[i]);
}
return (t_cost / 2);
}
int main()
{
string S = "aabbcccdeffffggghhhhhii" ;
cout << sortString(S);
return 0;
}
|
Java
import java.util.*;
class GFG{
public static int sortString(String S)
{
Vector<Integer> sorted = new Vector<Integer>();
Vector<Integer> original = new Vector<Integer>();
boolean insert = false ;
if (S.length() == 1 )
{
System.out.println( 0 );
}
int curr = 1 ;
for ( int i = 0 ; i < (S.length() - 1 ); i++)
{
if (S.charAt(i) == S.charAt(i + 1 ))
{
curr += 1 ;
insert = false ;
}
else
{
sorted.add(curr);
original.add(curr);
curr = 1 ;
insert = true ;
}
}
if ((S.charAt(S.length() - 1 ) !=
S.charAt(S.length() - 2 )) ||
insert == false )
{
sorted.add(curr);
original.add(curr);
}
Collections.sort(sorted);
int t_cost = 0 ;
for ( int i = 0 ; i < sorted.size(); i++)
{
t_cost += Math.abs(sorted.get(i) -
original.get(i));
}
return (t_cost / 2 );
}
public static void main(String[] args)
{
String S = "aabbcccdeffffggghhhhhii" ;
System.out.print(sortString(S));
}
}
|
Python3
def sortString(S):
sorted1 = []
original = []
insert = False
if ( len (S) = = 1 ):
print ( 0 )
curr = 1
for i in range ( len (S) - 1 ):
if (S[i] = = S[i + 1 ]):
curr + = 1
insert = False
else :
sorted1.append(curr)
original.append(curr)
curr = 1
insert = True
if ((S[( len (S) - 1 )] ! = S[( len (S) - 2 )]) or
insert = = False ):
sorted1.append(curr)
original.append(curr)
sorted1.sort()
t_cost = 0
for i in range ( len (sorted1)):
t_cost + = abs (sorted1[i] - original[i])
return (t_cost / / 2 )
if __name__ = = "__main__" :
S = "aabbcccdeffffggghhhhhii"
print (sortString(S))
|
C#
using System;
using System.Collections.Generic;
class GFG{
public static int sortString( string S)
{
List< int > sorted = new List< int >();
List< int > original = new List< int >();
bool insert = false ;
if (S.Length == 1)
{
Console.WriteLine(0);
}
int curr = 1;
for ( int i = 0; i < (S.Length - 1); i++)
{
if (S[i] == S[i + 1])
{
curr += 1;
insert = false ;
}
else
{
sorted.Add(curr);
original.Add(curr);
curr = 1;
insert = true ;
}
}
if ((S[S.Length - 1] !=
S[S.Length - 2]) || insert == false )
{
sorted.Add(curr);
original.Add(curr);
}
sorted.Sort();
int t_cost = 0;
for ( int i = 0; i < sorted.Count; i++)
{
t_cost += Math.Abs(sorted[i] -
original[i]);
}
return (t_cost / 2);
}
static void Main()
{
string S = "aabbcccdeffffggghhhhhii" ;
Console.Write(sortString(S));
}
}
|
Javascript
<script>
function sortString(S)
{
let sorted = [];
let original = [];
let insert = false ;
if (S.length == 1)
{
document.write(0 + "</br>" );
}
let curr = 1;
for (let i = 0; i < (S.length - 1); i++)
{
if (S[i] == S[i + 1])
{
curr += 1;
insert = false ;
}
else
{
sorted.push(curr);
original.push(curr);
curr = 1;
insert = true ;
}
}
if ((S[S.length - 1] !=
S[S.length - 2]) || insert == false )
{
sorted.push(curr);
original.push(curr);
}
sorted.sort( function (a, b){ return a - b});
let t_cost = 0;
for (let i = 0; i < sorted.length; i++)
{
t_cost += Math.abs(sorted[i] - original[i]);
}
return parseInt(t_cost / 2, 10);
}
let S = "aabbcccdeffffggghhhhhii" ;
document.write(sortString(S));
</script>
|
Time Complexity: O(NlogN)
Auxiliary Space: O(N)
Last Updated :
20 Apr, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...