Given string **str**, the task is to minimize the total cost to remove all the characters from the string in alphabetical order.

The cost of removing any character at i

^{ th}index from the string will bei. The indexing is 1-based.

**Examples:**

Input:str = “abcab”Output:8Explanation:

First char ‘a’ at index 1 is removed, str[] becomes “bcab”,

Then char ‘a’ with index 3 is removed, str[] becomes “bcb”

After that char ‘b’ with index 1 is removed, str[] becomes “cb”,

Then char ‘b’ with index 2 is removed, str[] becomes “c”,

Finally, char ‘c’ is removed.

Total points = 1+3 + 1 + 2 + 1 = 8.Input:str = “def”Output:3

**Naive Approach:** The simplest approach is to remove the smallest character with a smaller index in the string in each step and keep on adding the cost to the total cost. Print the final cost after this operation.

**Time Complexity:** O(N^{2})**Auxiliary Space:** O(1)

**Efficient Approach:** The above approach can be optimized by precomputing for each character, the number of smaller characters preceding it in the given string. Below are the steps:

- Initialize the total cost to
**0**. - Transverse the given string and for each character, count the number of characters that are less than the current character and have occurred before it.
- If this count is 0, this means that the current character will be removed at the present index, so add the index of the character to the resultant cost.
- Else subtract the count from its current index and then add it to the total cost.
- Print the total cost after all the above steps.

Below is the implementation of the above approach:

## C++

`// C++ program for the above approach` `#include <bits/stdc++.h>` `#include <vector>` `using` `namespace` `std;` `// Function to find the minimum cost` `// required to remove each character` `// of the string in alphabetical order` `int` `minSteps(string str, ` `int` `N)` `{` ` ` `int` `smaller, cost = 0;` ` ` `// Stores the frequency of` ` ` `// characters of the string` ` ` `int` `f[26] = { 0 };` ` ` `// Iterate through the string` ` ` `for` `(` `int` `i = 0; i < N; i++) {` ` ` `int` `curr_ele = str[i] - ` `'a'` `;` ` ` `smaller = 0;` ` ` `// Count the number of characters` ` ` `// smaller than the present character` ` ` `for` `(` `int` `j = 0; j <= curr_ele; j++) {` ` ` `if` `(f[j])` ` ` `smaller += f[j];` ` ` `}` ` ` `// If no smaller character` ` ` `// preceeds current character` ` ` `if` `(smaller == 0)` ` ` `cost += (i + 1);` ` ` `else` ` ` `cost += (i - smaller + 1);` ` ` `// Increase the frequency of` ` ` `// the current character` ` ` `f[str[i] - ` `'a'` `]++;` ` ` `}` ` ` `// Return the` ` ` `// total cost` ` ` `return` `cost;` `}` `// Driver Code` `int` `main()` `{` ` ` `// Given string str` ` ` `string str = ` `"abcab"` `;` ` ` `int` `N = str.size();` ` ` `// Function call` ` ` `cout << minSteps(str, N);` ` ` `return` `0;` `}` |

*chevron_right*

*filter_none*

## Java

`// Java program for ` `// the above approach` `import` `java.io.*;` `class` `GFG{` ` ` `// Function to find the minimum cost` ` ` `// required to remove each character` ` ` `// of the string in alphabetical order` ` ` `static` `int` `minSteps(String str, ` `int` `N)` ` ` `{` ` ` `int` `smaller, cost = ` `0` `;` ` ` `// Stores the frequency of` ` ` `// characters of the string` ` ` `int` `f[] = ` `new` `int` `[` `26` `];` ` ` `// Iterate through the string` ` ` `for` `(` `int` `i = ` `0` `; i < N; i++) ` ` ` `{` ` ` `int` `curr_ele = str.charAt(i) - ` `'a'` `;` ` ` `smaller = ` `0` `;` ` ` `// Count the number of characters` ` ` `// smaller than the present character` ` ` `for` `(` `int` `j = ` `0` `; j <= curr_ele; j++) ` ` ` `{` ` ` `if` `(f[j] != ` `0` `)` ` ` `smaller += f[j];` ` ` `}` ` ` `// If no smaller character` ` ` `// preceeds current character` ` ` `if` `(smaller == ` `0` `)` ` ` `cost += (i + ` `1` `);` ` ` `else` ` ` `cost += (i - smaller + ` `1` `);` ` ` `// Increase the frequency of` ` ` `// the current character` ` ` `f[str.charAt(i) - ` `'a'` `]++;` ` ` `}` ` ` `// Return the` ` ` `// total cost` ` ` `return` `cost;` ` ` `}` ` ` `// Driver Code` ` ` `public` `static` `void` `main(String[] args)` ` ` `{` ` ` `// Given string str` ` ` `String str = ` `"abcab"` `;` ` ` `int` `N = str.length();` ` ` `// Function call` ` ` `System.out.println(minSteps(str, N));` ` ` `}` `}` `// This code is contributed by AnkitRai01` |

*chevron_right*

*filter_none*

## Python3

`# Python3 program for the above approach ` `# Function to find the minimum cost` `# required to remove each character` `# of the string in alphabetical order ` `def` `minSteps(` `str` `, N):` ` ` `cost ` `=` `0` ` ` `# Stores the frequency of` ` ` `# characters of the string` ` ` `f ` `=` `[` `0` `] ` `*` `26` ` ` `# Iterate through the string` ` ` `for` `i ` `in` `range` `(N):` ` ` `curr_ele ` `=` `ord` `(` `str` `[i]) ` `-` `ord` `(` `'a'` `)` ` ` `smaller ` `=` `0` ` ` `# Count the number of characters` ` ` `# smaller than the present character` ` ` `for` `j ` `in` `range` `(curr_ele ` `+` `1` `):` ` ` `if` `(f[j]):` ` ` `smaller ` `+` `=` `f[j]` ` ` `# If no smaller character` ` ` `# preceeds current character` ` ` `if` `(smaller ` `=` `=` `0` `):` ` ` `cost ` `+` `=` `(i ` `+` `1` `)` ` ` `else` `:` ` ` `cost ` `+` `=` `(i ` `-` `smaller ` `+` `1` `)` ` ` `# Increase the frequency of` ` ` `# the current character` ` ` `f[` `ord` `(` `str` `[i]) ` `-` `ord` `(` `'a'` `)] ` `+` `=` `1` ` ` `# Return the total cost` ` ` `return` `cost` `# Driver Code` `# Given string str` `str` `=` `"abcab"` `N ` `=` `len` `(` `str` `)` `# Function call` `print` `(minSteps(` `str` `, N))` `# This code is contributed by Shivam Singh` |

*chevron_right*

*filter_none*

## C#

`// C# program for ` `// the above approach` `using` `System;` `class` `GFG{` `// Function to find the minimum cost` `// required to remove each character` `// of the string in alphabetical order` `static` `int` `minSteps(` `string` `str, ` `int` `N)` `{` ` ` `int` `smaller, cost = 0;` ` ` `// Stores the frequency of` ` ` `// characters of the string` ` ` `int` `[] f = ` `new` `int` `[26];` ` ` `// Iterate through the string` ` ` `for` `(` `int` `i = 0; i < N; i++) ` ` ` `{` ` ` `int` `curr_ele = str[i] - ` `'a'` `;` ` ` `smaller = 0;` ` ` `// Count the number of characters` ` ` `// smaller than the present character` ` ` `for` `(` `int` `j = 0; j <= curr_ele; j++) ` ` ` `{` ` ` `if` `(f[j] != 0)` ` ` `smaller += f[j];` ` ` `}` ` ` ` ` `// If no smaller character` ` ` `// preceeds current character` ` ` `if` `(smaller == 0)` ` ` `cost += (i + 1);` ` ` `else` ` ` `cost += (i - smaller + 1);` ` ` `// Increase the frequency of` ` ` `// the current character` ` ` `f[str[i] - ` `'a'` `]++;` ` ` `}` ` ` `// Return the` ` ` `// total cost` ` ` `return` `cost;` `}` `// Driver Code` `public` `static` `void` `Main()` `{` ` ` `// Given string str` ` ` `string` `str = ` `"abcab"` `;` ` ` `int` `N = str.Length;` ` ` `// Function call` ` ` `Console.Write(minSteps(str, N));` `}` `}` `// This code is contributed by Chitranayal` |

*chevron_right*

*filter_none*

**Output:**

8

**Time Complexity:** O(N)**Auxiliary Space:** O(26)

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:

- Minimum cost to empty Array where cost of removing an element is 2^(removed_count) * arr[i]
- Maximize cost to empty given array by repetitively removing K array elements
- Maximize cost to empty an array by removing contiguous subarrays of equal elements
- Replace consonants with next immediate consonants alphabetically in a String
- Minimize Cost to sort a String in Increasing Order of Frequencies of Characters
- Minimize cost to convert all characters of a binary string to 0s
- Sort an Array alphabetically when each number is converted into words
- Minimum cost to remove the spaces between characters of a String by rearranging the characters
- Cost required to empty a given array by repeated removal of maximum obtained by given operations
- Find the winner of a game of removing any number of stones from the least indexed non-empty pile from given N piles
- Maximum non-repeating characters after removing K characters
- Minimize cost to replace all the vowels of a given String by a single vowel
- Minimize cost to convert given string into concatenation of equal substrings of length K
- Minimize cost to convert given string to a palindrome
- Minimize the length of string by removing occurrence of only one character
- Longest subarray of non-empty cells after removal of at most a single empty cell
- Sum of indices of Characters removed to obtain an Empty String based on given conditions
- Minimize cost to convert given two integers to zero using given operations
- Steps to make array empty by removing maximum and its right side
- Empty an Array by removing maximum of K value from it

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.