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_: _
Input :_ S = “aaaa” _
Output :_ 0 _
Approach:
Follow the steps below to solve the problem:
Below is the implementation of the above approach:
#include <bits/stdc++.h>
**using**
**namespace**
std;
**int**
sortString(string S)
{
vector<``**int**``> sorted, original;
**bool**
insert =
**false**``;
// For a single character
**if**
(S.length() == 1) {
cout << 0 << endl;
}
// Stores count of repetitions
// of a character
**int**
curr = 1;
**for**
(``**int**
i = 0; i < (S.length() - 1); i++) {
// If repeating character
**if**
(S[i] == S[i + 1]) {
curr += 1;
insert =
**false**``;
}
// Otherwise
**else**
{
// Store frequency
sorted.push_back(curr);
original.push_back(curr);
// Reset count
curr = 1;
insert =
**true**``;
}
}
// Insert the last character block
**if**
((S[(S.length() - 1)] != S[(S.length() - 2)])
|| insert ==
**false**``) {
sorted.push_back(curr);
original.push_back(curr);
}
// Sort the frequencies
sort(sorted.begin(), sorted.end());
// Stores the minimum cost of all operations
**int**
t_cost = 0;
**for**
(``**int**
i = 0; i < sorted.size(); i++) {
// Store the absolute difference of
// i-th frequencies of ordered and
// unordered sequences
t_cost +=
**abs**``(sorted[i] - original[i]);
}
// Return the minimum cost
**return**
(t_cost / 2);
}
// Driver Code
**int**
main()
{
string S =
"aabbcccdeffffggghhhhhii"``;
cout << sortString(S);
**return**
0;
}
Output:
5
Time Complexity:_ O(NlogN)_
Auxiliary Space:_ O(N)_
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
#greedy #mathematical #sorting #strings #frequency-counting #arrays