Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Sorting
  • MCQs on Sorting
  • Tutorial on Sorting
  • Bubble Sort
  • Quick Sort
  • Merge Sort
  • Insertion Sort
  • Selection Sort
  • Heap Sort
  • Sorting Complexities
  • Radix Sort
  • ShellSort
  • Counting Sort
  • Bucket Sort
  • TimSort
  • Bitonic Sort
  • Uses of Sorting Algorithm
Open In App
Next Article:
Minimize deletions such that sum of position of characters is at most K
Next article icon

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

Last Updated : 08 Feb, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

C++
// C++ code for the above approach: #include <bits/stdc++.h> using namespace std;  int minAsciiSum(string s, int k) {     int freq[26] = { 0 };     for (int i = 0; i < s.length(); i++) {         freq[s[i] - 'a']++;     }     sort(s.begin(), s.end());     int sum = 0, removed = 0;     for (int i = 0; i < s.length(); i++) {         int ch = s[i] - 'a';         if (freq[ch] > k - removed) {             sum += (k - removed) * (s[i]);             removed = k;             break;         }         else {             sum += freq[ch] * (s[i]);             removed += freq[ch];             freq[ch] = 0;         }         if (removed == k) {             break;         }     }     if (removed < k) {         sum += (k - removed) * (s[s.length() - 1]);     }     return sum; }  // Drivers code int main() {     string s = "abaacd";     int k = 3;      // Function Call     cout << minAsciiSum(s, k) << endl;     return 0; } 
Java
// Java code for the above approach: import java.util.*;  class GFG {     static int minAsciiSum(String s, int k)     {         int freq[] = new int[26];         for (int i = 0; i < s.length(); i++) {             freq[s.charAt(i) - 'a']++;         }         char[] ch = s.toCharArray();         Arrays.sort(ch);         s = new String(ch);         int sum = 0, removed = 0;         for (int i = 0; i < s.length(); i++) {             int ch1 = s.charAt(i) - 'a';             if (freq[ch1] > k - removed) {                 sum += (k - removed) * (s.charAt(i));                 removed = k;                 break;             }             else {                 sum += freq[ch1] * (s.charAt(i));                 removed += freq[ch1];                 freq[ch1] = 0;             }             if (removed == k) {                 break;             }         }         if (removed < k) {             sum += (k - removed)                    * (s.charAt(s.length() - 1));         }         return sum;     }      // Driver code     public static void main(String[] args)     {         String s = "abaacd";         int k = 3;          // Function Call         System.out.println(minAsciiSum(s, k));     } } // This code is contributed by Tapesh(tapeshdua420) 
Python3
# python code for the above approach:  def minAsciiSum(s, k):     freq = [0] * 26     for ch in s:         freq[ord(ch) - ord('a')] += 1     s = sorted(s)     sum = 0     removed = 0     for ch in s:         idx = ord(ch) - ord('a')         if freq[idx] > k - removed:             sum += (k - removed) * ord(ch)             removed = k             break         else:             sum += freq[idx] * ord(ch)             removed += freq[idx]             freq[idx] = 0         if removed == k:             break     if removed < k:         sum += (k - removed) * ord(s[-1])     return sum  # Driver Code if __name__ == '__main__':     s = "abaacd"     k = 3     # Function Call     print(minAsciiSum(s, k)) 
C#
//  C# code for the above approach: using System; using System.Linq;  class GFG {     static int MinAsciiSum(string s, int k)     {         int[] freq = new int[26];          // Calculate the frequency of each character in the         // input string 's'         foreach (char c in s)         {             freq[c - 'a']++;         }          // Sort the string in ascending order         char[] sortedS = s.OrderBy(c => c).ToArray();          int sum = 0, removed = 0;          // Loop through the sorted string 'sortedS'         for (int i = 0; i < sortedS.Length; i++)         {             char ch = sortedS[i];             int charIndex = ch - 'a';              // Check if the frequency of the current character             // is greater than 'k - removed'             if (freq[charIndex] > k - removed)             {                 // Add the sum of ASCII values of (k - removed)                 // instances of the character 'ch' to 'sum'                 sum += (k - removed) * ch;                 removed = k;                 break;             }             else             {                 // Add the sum of ASCII values of all instances of                 // the character 'ch' to 'sum'                 sum += freq[charIndex] * ch;                 // Update 'removed' by adding the frequency of                 // the current character to it                 removed += freq[charIndex];                 // Set the frequency of the character to zero to                 // mark it as "removed"                 freq[charIndex] = 0;             }              // Check if we have removed 'k' characters,            // break out of the loop             if (removed == k)             {                 break;             }         }          // If 'removed' is still less than 'k', add the sum         // of ASCII values of (k - removed) instances of the last        // character in the sorted string         if (removed < k)         {             char lastChar = sortedS[sortedS.Length - 1];             sum += (k - removed) * lastChar;         }          return sum;     } //Driver code     static void Main()     {         string s = "abaacd";         int k = 3;          // Function Call         Console.WriteLine(MinAsciiSum(s, k));     } } 
JavaScript
// JavaScript code for the above approach:  function minAsciiSum(s, k) {   let freq = new Array(26).fill(0);   for (let ch of s) {     freq[ch.charCodeAt(0) - 'a'.charCodeAt(0)] += 1;   }   s = s.split('').sort().join('');   let sum = 0;   let removed = 0;   for (let ch of s) {     let idx = ch.charCodeAt(0) - 'a'.charCodeAt(0);     if (freq[idx] > k - removed) {       sum += (k - removed) * ch.charCodeAt(0);       removed = k;       break;     } else {       sum += freq[idx] * ch.charCodeAt(0);       removed += freq[idx];       freq[idx] = 0;     }     if (removed === k) {       break;     }   }   if (removed < k) {     sum += (k - removed) * s.charCodeAt(s.length - 1);   }   return sum; }  // Driver Code let s = "abaacd"; let k = 3; // Function Call console.log(minAsciiSum(s, k));  // This code is contributed by Tapesh(tapeshdua420) 

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.


Next Article
Minimize deletions such that sum of position of characters is at most K
author
vishaldhaygude01
Improve
Article Tags :
  • Strings
  • Greedy
  • Sorting
  • DSA
  • ASCII
Practice Tags :
  • Greedy
  • Sorting
  • Strings

Similar Reads

  • Maximize ascii sum removing K characters in String
    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 maximized. Examples: Input: s = "word", K = 2Output: 233Explanation: We need to remove exactly 2
    9 min read
  • Minimize deletions such that sum of position of characters is at most K
    Given a string S consisting of lower case letters and an integer K, the task is to remove minimum number of letters from the string, such that the sum of alphabetic ordering of the letters present in the string is at most K. Examples : Input: S = "abca", K = 2Output: "aa"Explanation: Initial sum for
    8 min read
  • Minimum K such that every substring of length atleast K contains a character c
    Given a string S containing lowercase latin letters. A character c is called K-amazing if every substring of S with length atleast K contains this character c. Find the minimum possible K such that there exists atleast one K-amazing character. Examples: Input : S = "abcde" Output :3 Explanation : Ev
    11 min read
  • Remove minimum characters so that two strings become anagram
    Given two strings in lowercase, the task is to make them anagrams. The only allowed operation is to remove a character from any string. Find the minimum number of characters to be deleted to make both the strings anagram. Two strings are called anagrams of each other if one of them can be converted
    12 min read
  • Minimum replacements in a string to make adjacent characters unequal
    Given a lowercase character string str of size N. In one operation any character can be changed into some other character. The task is to find the minimum number of operations such that no two adjacent characters are equal.Examples: Input: Str = "caaab" Output: 1 Explanation: Change the second a to
    6 min read
  • Minimum characters to be replaced to remove the given substring
    Given two strings str1 and str2. The task is to find the minimum number of characters to be replaced by $ in string str1 such that str1 does not contain string str2 as any substring. Examples: Input: str1 = "intellect", str2 = "tell" Output: 1 4th character of string "str1" can be replaced by $ such
    7 min read
  • Minimum characters to be replaced in given String to make all characters same
    Given a string str of size N consisting of lowercase English characters, the task is to find the minimum characters to be replaced to make all characters of string str same. Any character can be replaced by any other character. Example: Input: str="geeksforgeeks"Output: 9Explanation: Replace all the
    7 min read
  • Minimum removals required such that given string consists only of a pair of alternating characters
    Given a string S, the task is to find the minimum removal of characters required such that the string S consists only of two alternating characters. Examples: Input: S = "adebbeeaebd"Output: 7Explanation: Removing all occurrences of 'b' and 'e' modifies the string to "adad", which consist of alterna
    10 min read
  • Minimum cost to delete characters from String A to remove any subsequence as String B
    Given two strings A and B of size N and M respectively, where B is a sub-sequence of A and an array arr[] of size N, where arr[i] is the cost to delete ith character from string A. The task is to find the minimum cost to delete characters from A such that after deletion no subsequence of A is the sa
    15+ min read
  • Minimum removal of characters required such that permutation of given string is a palindrome
    Given string str consisting of lowercase letters, the task is to find the minimum number of characters to be deleted from the given string such that any permutation of the remaining string is a palindrome. Examples: Input: str="aba"Output: 1Explanation: Removing 'b' generates a palindromic string "a
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences