VOOZH about

URL: https://www.geeksforgeeks.org/dsa/remove-k-characters-in-a-string-such-that-ascii-sum-is-minimum/

⇱ Remove k characters in a String such that ASCII sum is minimum - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Remove k characters in a String such that ASCII sum is minimum

Last Updated : 23 Jul, 2025

Given a string s and an integer k, the task is to remove k characters from the string such that the sum of ASCII (American Standard Code for Information Interchange) values of the remaining characters is minimized.

Examples:

Input: s = "ABbc", k = 2
Output: 131
Explanation: We need to remove exactly 2 characters from the string "ABbc" to minimize the ASCII sum of the remaining characters. By removing 'b' and 'c', we obtain the minimum sum of 131, which corresponds to the ASCII sum of the remaining characters ('A' and 'B').

Input: s = "abaacd", k = 3
Output: 291
Explanation: We need to remove exactly 3 characters from the string "abaacd" to minimize the ASCII sum of the remaining characters. By removing 'b', 'c', and 'd', we obtain the minimum sum of 297, which corresponds to the ASCII sum of the remaining characters ('a', 'a', and 'a').

Approach: To solve the problem follow the below idea:

To solve this problem, we can use a Greedy approach. The idea is to sort the characters of the given string in ascending order of their ASCII values, and then remove k characters from the end of the sorted string. This approach ensures that we are removing characters with the highest ASCII values, which will result in the minimum sum of the remaining characters.

Here are the steps of the approach:

  • Create an array to store the frequency of each character in the string s.
  • Sort the characters of the string s in ascending order of their ASCII values.
  • Traverse the sorted string s, and for each character, decrement its frequency in the frequency array.
  • While traversing the sorted string s, keep track of the number of characters removed so far.
    • If the current character has a frequency greater than k, then remove k characters from the end of the sorted string s, and break the loop.
    • Otherwise, remove all the characters of the current character from the end of the sorted string s, and subtract its ASCII value multiplied by its frequency from the sum of the remaining characters.
    • If k characters have been removed, then break the loop.
  • If the loop completes without breaking, then remove the remaining k characters from the end of the sorted string s, and subtract their ASCII values from the sum of the remaining characters.
  • Return the sum of the remaining characters.

Below is the implementation of the above approach:


Output
291

Time Complexity: O(n*logn), where n is the length of the string.
Auxiliary Space: O(1), because we are using a fixed-size array of size 26 to store the frequency of each character in the string.

Comment
Article Tags: