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
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
Find smallest string with whose characters all given Strings can be generated
Next article icon

Generate longest String with character sum at most K by deleting letters

Last Updated : 21 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string str and an integer K, the task is to find the longest string that can be made by deleting letters from the given string such that the sum of the characters of the remaining string is at most K.

Note: The value of the string is calculated as the sum of the value of characters (a value is 1, b value is 2...., z value is 26).

Examples:

Input:  str = "geeksforgeeks", K = 15
Output: eee
Explanation: After deleting the characters string gets reduced to eee whose value is 5 + 5 +  5 = 15 which is less than or equal to K i.e. 15

Input: str = "abca", K = 6
Output: aba
Explanation: Initial value of str 1 + 2 + 3 + 1 = 7, after deleting the letter c, the string gets reduced to aba whose value is 1+2+1 = 4 which is less than K i.e. 6.

Approach: The problem can be solved using Greedy approach based on the following idea:

We must delete letters with the highest value first. So, we sort the string str in decreasing order and will be deleting letters from the starting of string str as long as the initial value of string str is greater than the given value K.

Follow the steps mentioned below to implement the idea:

  • Calculate the initial value of the given string.
  • Sort the string str in decreasing order
  • Start removing the value of the current letter from the initial value as long as the initial value is greater than K.
    • Store the removed characters in the map
  • Iterate through the given string once again and 
    • If the current letter does not exist in the map take it into the resultant string
    • Else decrease the frequency of the letter
  • Return the resultant string

Below is the implementation of the above approach:

C++
// C++ code to implement the approach  #include <bits/stdc++.h> using namespace std;  // Function for finding out string with value // less than or equal to K string minimise_str(string str, int K) {     int initial_value = 0;      // Calculate initial value of string     for (int i = 0; i < str.length(); i++) {         initial_value += (str[i] - 'a') + 1;     }      string temp = str;      // Sort the string in decreasing order     sort(str.begin(), str.end());     reverse(str.begin(), str.end());      // Store the deleted letters     unordered_map<char, int> mpp;     int i = 0;      // Remove letters as long as the initial     // value is greater than K     while (initial_value > K) {         initial_value -= (str[i] - 'a') + 1;         mpp[str[i]]++;         i++;     }      // Store resultant string     string ans = "";     for (int i = 0; i < temp.size(); i++) {          // If letter do exist in map, decrease         // frequency         if (mpp[temp[i]] > 0) {             mpp[temp[i]]--;         }         // Else store the letter in resultant         // string         else {             ans += temp[i];         }     }      // Return resultant string     return ans; }  // Driver code int main() {     string str = "geeksforgeeks";     int K = 15;      // Function call     cout << minimise_str(str, K);      return 0; } 
Java
// Java code to implement the approach  import java.io.*; import java.util.*;  class GFG {      // Function for finding out string with value less than     // or equal to K     static String minimiseStr(String str, int K)     {         int initialValue = 0;          // Calculate initial value of string         for (int i = 0; i < str.length(); i++) {             initialValue += (str.charAt(i) - 'a') + 1;         }          String temp = str;          // Sort the string in decreasing order         char[] chars = str.toCharArray();         Arrays.sort(chars);         str = new StringBuilder(new String(chars))                   .reverse()                   .toString();          // Store the deleted letters         Map<Character, Integer> mpp = new HashMap<>();         int i = 0;          // Remove letters as long as the initial value is         // greater than K         while (initialValue > K) {             initialValue -= (str.charAt(i) - 'a') + 1;             mpp.put(str.charAt(i),                     mpp.getOrDefault(str.charAt(i), 0) + 1);             i++;         }          // Store resultant string         StringBuilder ans = new StringBuilder();         for (int j = 0; j < temp.length(); j++) {              // If letter do exist in map, decrease frequency             if (mpp.containsKey(temp.charAt(j))                 && mpp.get(temp.charAt(j)) > 0) {                 int freq = mpp.get(temp.charAt(j));                 mpp.put(temp.charAt(j), freq - 1);             }             // Else store the letter in resultant string             else {                 ans.append(temp.charAt(j));             }         }          // Return resultant string         return ans.toString();     }      public static void main(String[] args)     {         String str = "geeksforgeeks";         int K = 15;          // Function call         System.out.println(minimiseStr(str, K));     } }  // This code is contributed by karthik. 
Python3
# python code imple.  import collections  def minimise_str(str, K):     initial_value = 0      # Calculate initial value of string     for i in range(len(str)):         initial_value += (ord(str[i]) - ord('a') + 1)      temp = str      # Sort the string in decreasing order     str = ''.join(sorted(str, reverse=True))      # Store the deleted letters     mpp = collections.defaultdict(int)     i = 0      # Remove letters as long as the initial     # value is greater than K     while initial_value > K:         initial_value -= (ord(str[i]) - ord('a') + 1)         mpp[str[i]] += 1         i += 1      # Store resultant string     ans = ""     for i in range(len(temp)):          # If letter do exist in map, decrease         # frequency         if mpp[temp[i]] > 0:             mpp[temp[i]] -= 1         # Else store the letter in resultant         # string         else:             ans += temp[i]      # Return resultant string     return ans  # Driver code str = "geeksforgeeks" K = 15  # Function call print(minimise_str(str, K))  #code by ksam24000 
C#
using System; using System.Collections.Generic; using System.Linq;  class GFG { // Function for finding out string with value // less than or equal to K static string MinimiseString(string str, int K) { int initial_value = 0;       // Calculate initial value of string     foreach (char c in str)     {         initial_value += (c - 'a') + 1;     }      string temp = str;      // Sort the string in decreasing order     char[] arr = str.ToCharArray();     Array.Sort(arr);     Array.Reverse(arr);     str = new string(arr);      // Store the deleted letters     Dictionary<char, int> mpp = new Dictionary<char, int>();     int i = 0;      // Remove letters as long as the initial     // value is greater than K     while (initial_value > K)     {         initial_value -= (str[i] - 'a') + 1;         if (mpp.ContainsKey(str[i]))         {             mpp[str[i]]++;         }         else         {             mpp[str[i]] = 1;         }         i++;     }      // Store resultant string     string ans = "";     foreach (char c in temp)     {         // If letter do exist in map, decrease         // frequency         if (mpp.ContainsKey(c) && mpp[c] > 0)         {             mpp[c]--;         }         // Else store the letter in resultant         // string         else         {             ans += c;         }     }      // Return resultant string     return ans; }  // Driver code static void Main(string[] args) {     string str = "geeksforgeeks";     int K = 15;      // Function call     Console.WriteLine(MinimiseString(str, K)); } } 
JavaScript
function minimiseStr(str, K) {   let initialValue = 0;    // Calculate initial value of string   for (let i = 0; i < str.length; i++) {     initialValue += (str.charCodeAt(i) - 'a'.charCodeAt(0)) + 1;   }    let temp = str;    // Sort the string in decreasing order   str = str.split('').sort().reverse().join('');    // Store the deleted letters   let mpp = {};   let i = 0;    // Remove letters as long as the initial   // value is greater than K   while (initialValue > K) {     initialValue -= (str.charCodeAt(i) - 'a'.charCodeAt(0)) + 1;     if (mpp[str[i]]) {       mpp[str[i]]++;     } else {       mpp[str[i]] = 1;     }     i++;   }    // Store resultant string   let ans = '';   for (let i = 0; i < temp.length; i++) {     // If letter do exist in map, decrease     // frequency     if (mpp[temp[i]] > 0) {       mpp[temp[i]]--;     }     // Else store the letter in resultant     // string     else {       ans += temp[i];     }   }    // Return resultant string   return ans; }  // Driver code let str = 'geeksforgeeks'; let K = 15; //Function call document.write(minimiseStr(str, K)); 

Output
eee

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

Related Articles:

  • Introduction to String - Data Structure and Algorithm Tutorials
  • Introduction to Greedy Algorithm - Data Structure and Algorithm Tutorials

Next Article
Find smallest string with whose characters all given Strings can be generated

H

harsh2024it1034
Improve
Article Tags :
  • Strings
  • Greedy
  • Technical Scripter
  • DSA
  • Technical Scripter 2022
Practice Tags :
  • Greedy
  • Strings

Similar Reads

  • Find length of longest substring with at most K normal characters
    Given a string P consisting of small English letters and a 26-digit bit string Q, where 1 represents the special character and 0 represents a normal character for the 26 English alphabets. The task is to find the length of the longest substring with at most K normal characters. Examples: Input : P =
    12 min read
  • Find smallest string with whose characters all given Strings can be generated
    Given an array of strings arr[]. The task is to generate the string which contains all the characters of all the strings present in array and smallest in size. There can be many such possible strings and any one is acceptable. Examples: Input: arr[] = {"your", "you", "or", "yo"}Output: ruyoExplanati
    5 min read
  • Minimum K such that every substring of length at least K contains a character c | Set-2
    Given a string S consisting of N lowercase English alphabets, and also given that a character C is called K-amazing, if every substring of length at least K contains this character C, the task is to find the minimum possible K such that there exists at least one K-amazing character. Examples: Input:
    8 min read
  • Counting K-Length Strings with Fixed Character in a Unique String
    Given a string S of length n containing distinct characters and a character C , the task is to count k-length strings that can be formed using characters from the string S, ensuring each string includes the specified character C, and no characters from the given string S are used more than once. Ret
    9 min read
  • Minimize String length by deleting Substring of same character when K flips are allowed
    Given a binary string consisting of '0' and '1' only and an integer K, the task is to minimize the string as far as possible by deleting a substring of the same character, when you can flip at most K characters. Examples: Input: S = "0110", K = 2Output: 0Explanation: We can make two '0' s into '1' o
    12 min read
  • Longest sub-string having frequency of each character less than equal to k
    Given a string str of length n. The problem is to find the length of the longest sub-string in str having frequency of each character less than equal to the given value k. Examples : Input : str = "babcaag", k = 1 Output : 3 abc and bca are the two longest sub-strings having frequency of each charac
    10 min read
  • Find characters which when increased by K are present in String
    Given a string s of lowercase English alphabets and integer K. the task is to check if each character after increasing their ASCII by K is present in the string or not. Return only unique characters and the first index where they are present. Examples: Input: s = "dszepvaxuo", k = 3Output: {{1, 's'}
    8 min read
  • Length of longest substring having all characters as K
    Given a string S and a character K. The task is to find the length of the longest substring of S having all characters the same as character K. Examples: Input: S = "abcd1111aabc", K = '1' Output: 4 Explanation: 1111 is the largest substring of length 4. Input: S = "#1234#@@abcd", K = '@' Output: 2
    8 min read
  • Longest substring with atmost K characters from the given set of characters
    Given a string S, an integer K and set of characters Q[], the task is to find the longest substring in string S which contains atmost K characters from the given character set Q[].Examples: Input: S = "normal", Q = {"a", "o", "n", "m", "r", "l"}, K = 1 Output: 1Explanation: All the characters in the
    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
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