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 be i. The indexing is 1-based.
Input: str = “abcab”
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”
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(N2)
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:
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.