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:5Explanation:

- 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 ` `using` `namespace` `std; ` `int` `sortString(string S) ` `{ ` ` ` `vector 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; ` `} ` |

*chevron_right*

*filter_none*

## Java

`// Java program to implement ` `// above approach` `import` `java.util.*;` `class` `GFG{` ` ` `public` `static` `int` `sortString(String S) ` `{ ` ` ` `Vector sorted = ` `new` `Vector();` ` ` `Vector original = ` `new` `Vector(); ` ` ` `boolean` `insert = ` `false` `; ` ` ` `// For a single character ` ` ` `if` `(S.length() == ` `1` `) ` ` ` `{ ` ` ` `System.out.println(` `0` `);` ` ` `} ` ` ` `// Stores count of repetitions ` ` ` `// of a character ` ` ` `int` `curr = ` `1` `; ` ` ` `for` `(` `int` `i = ` `0` `; i < (S.length() - ` `1` `); i++)` ` ` `{` ` ` ` ` `// If repeating character ` ` ` `if` `(S.charAt(i) == S.charAt(i + ` `1` `))` ` ` `{ ` ` ` `curr += ` `1` `; ` ` ` `insert = ` `false` `; ` ` ` `} ` ` ` `// Otherwise ` ` ` `else` ` ` `{` ` ` ` ` `// Store frequency ` ` ` `sorted.add(curr); ` ` ` `original.add(curr); ` ` ` `// Reset count ` ` ` `curr = ` `1` `; ` ` ` `insert = ` `true` `; ` ` ` `} ` ` ` `} ` ` ` `// Insert the last character block ` ` ` `if` `((S.charAt(S.length() - ` `1` `) != ` ` ` `S.charAt(S.length() - ` `2` `)) || ` ` ` `insert == ` `false` `) ` ` ` `{ ` ` ` `sorted.add(curr); ` ` ` `original.add(curr); ` ` ` `} ` ` ` `// Sort the frequencies ` ` ` `Collections.sort(sorted); ` ` ` `// 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 += Math.abs(sorted.get(i) - ` ` ` `original.get(i)); ` ` ` `} ` ` ` `// Return the minimum cost ` ` ` `return` `(t_cost / ` `2` `); ` `} ` `// Driver code` `public` `static` `void` `main(String[] args)` `{` ` ` `String S = ` `"aabbcccdeffffggghhhhhii"` `; ` ` ` `System.out.print(sortString(S));` `}` `}` `// This code is contributed by divyeshrabadiya07` |

*chevron_right*

*filter_none*

## Python3

`# Python program to implement` `# the above approach` `def` `sortString(S):` ` ` `sorted1 ` `=` `[]` ` ` `original ` `=` `[]` ` ` `insert ` `=` `False` ` ` `# For a single character` ` ` `if` `(` `len` `(S) ` `=` `=` `1` `):` ` ` `print` `(` `0` `)` ` ` `# Stores count of repetitions` ` ` `# of a character` ` ` `curr ` `=` `1` ` ` `for` `i ` `in` `range` `(` `len` `(S) ` `-` `1` `):` ` ` `# If repeating character` ` ` `if` `(S[i] ` `=` `=` `S[i ` `+` `1` `]):` ` ` `curr ` `+` `=` `1` ` ` `insert ` `=` `False` ` ` `# Otherwise` ` ` `else` `:` ` ` `# Store frequency` ` ` `sorted1.append(curr)` ` ` `original.append(curr)` ` ` `# Reset count` ` ` `curr ` `=` `1` ` ` `insert ` `=` `True` ` ` `# Insert the last character block` ` ` `if` `((S[(` `len` `(S) ` `-` `1` `)] !` `=` `S[(` `len` `(S) ` `-` `2` `)]) ` `or` ` ` `insert ` `=` `=` `False` `):` ` ` `sorted1.append(curr)` ` ` `original.append(curr)` ` ` `# Sort the frequencies` ` ` `sorted1.sort()` ` ` `# Stores the minimum cost of all operations` ` ` `t_cost ` `=` `0` ` ` `for` `i ` `in` `range` `(` `len` `(sorted1)):` ` ` ` ` `# Store the absolute difference of` ` ` `# i-th frequencies of ordered and` ` ` `# unordered sequences` ` ` `t_cost ` `+` `=` `abs` `(sorted1[i] ` `-` `original[i])` ` ` `# Return the minimum cost` ` ` `return` `(t_cost ` `/` `/` `2` `)` `# Driver Code` `if` `__name__ ` `=` `=` `"__main__"` `:` ` ` `S ` `=` `"aabbcccdeffffggghhhhhii"` ` ` `print` `(sortString(S))` `# This code is contributed by Chitranayal` |

*chevron_right*

*filter_none*

**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.

## Recommended Posts:

- Generate a Number in Decreasing order of Frequencies of characters of a given String
- Minimize cost to empty a given string by removing characters alphabetically
- Print characters and their frequencies in order of occurrence
- Print characters having odd frequencies in order of occurrence
- Print characters and their frequencies in order of occurrence using a LinkedHashMap in Java
- Print characters having even frequencies in order of occurrence
- Print characters having prime frequencies in order of occurrence
- Print characters and their frequencies in order of occurrence using Binary Tree
- Sort all even numbers in ascending order and then sort all odd numbers in descending order
- Minimum cost to remove the spaces between characters of a String by rearranging the characters
- Binary string with given frequencies of sums of consecutive pairs of characters
- Sum and Product of Prime Frequencies of Characters in a String
- XOR of Prime Frequencies of Characters in a String
- Check whether the frequencies of all the characters in a string are prime or not
- Character whose frequency is equal to the sum of frequencies of other characters of the given string
- Minimize length of prefix of string S containing all characters of another string T
- Sort even-placed elements in increasing and odd-placed in decreasing order
- Sort a Matrix in all way increasing order
- Python | Sort Tuples in Increasing Order by any key
- Sort only non-prime numbers of an array in increasing order

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.