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.
Examples:
Input: str = “abcab”
Output: 8
Explanation:
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(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:
// 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
// precedes 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;
} |
// 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
// precedes 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 |
# 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
# precedes 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 |
// 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
// precedes 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 |
<script> // JavaScript program for // the above approach // Function to find the minimum cost // required to remove each character // of the string in alphabetical order function minSteps(str, N)
{ var smaller,
cost = 0;
// Stores the frequency of
// characters of the string
var f = new Array(26).fill(0);
// Iterate through the string
for ( var i = 0; i < N; i++)
{
var curr_ele = str[i].charCodeAt(0) -
"a" .charCodeAt(0);
smaller = 0;
// Count the number of characters
// smaller than the present character
for ( var j = 0; j <= curr_ele; j++)
{
if (f[j] !== 0)
smaller += f[j];
}
// If no smaller character
// precedes current character
if (smaller === 0)
cost += i + 1;
else cost += i - smaller + 1;
// Increase the frequency of
// the current character
f[str[i].charCodeAt(0) -
"a" .charCodeAt(0)]++;
}
// Return the
// total cost
return cost;
} // Driver Code // Given string str var str = "abcab" ;
var N = str.length;
// Function call document.write(minSteps(str, N)); // This code is contributed by rdtank </script> |
8
Time Complexity: O(N)
Auxiliary Space: O(26)