Game with String | Practice | GeeksforGeeks

Given a string s of lowercase alphabets and a number k, the task is to print the minimum value of the string after removal of ‘k’ characters. The value of a string is defined as the sum of squares of the count of each distinct character.
 
Example 1:
Input: s = abccc, k = 1
Output: 6
Explaination:
We remove c to get the value as 12 + 12 + 22

 
Example 2:
Input: s = aabcbcbcabcc, k = 3
Output: 27
Explaination: We remove two 'c' and one 'b'. 
Now we get the value as 32 + 32 + 32.

Your Task:
You do not need to read input or print anything. Your task is to complete the function minValue() which takes s and k as input parameters and returns the minimum possible required value.
 
Expected Time Complexity: O(N*logN)  where N is the length of string
Expected Auxiliary Space: O(N)
 
Constraints:
1 ≤ k ≤ |string length| ≤ 100
0
rawatchirag7123 weeks ago
int minValue(string s, int k){       // code here       map<int,int>mp;       vector<int>v;       //count the value       for(int i=0;i<s.size();i++)       {           if(mp.find(s[i])==mp.end())           {               mp[s[i]]=1;           }           else           mp[s[i]]++;       }       //push frequence in vector        for (auto& it : mp) {               v.push_back(it.second);   }   int n=v.size()-1;   //minus the highest value by one    //so sort the vector in descending order   //then minus the first index of vector by one    while(k--)   {      sort(v.begin(),v.end(),greater<>());       v[0]=v[0]-1;          }   int sum=0;   //finally calculate squares of the count    for(int i=0;i<=n;i++)   {       sum+=v[i]*v[i];   }   return sum;   }
0
kartikeykabdwal863 weeks ago
   :)                       C++ || EASY TO UNDERSTAND 
 
class Solution{
public:
   int minValue(string s, int k){
      vector<int>v(26,0);
      priority_queue<int>pq;
      for(int i=0;i<s.size();i++)
      {
          v[s[i]-97]++;
          
      }
      for(int i=0;i<26;i++)
      {
          pq.push(v[i]);
      }
      while(k--)
      {
          int x=pq.top();
          x-=1;
          pq.pop();
          pq.push(x);
      }
      int ans=0;
     
      while(!pq.empty())
      {
           ans+=pq.top()*pq.top();
          pq.pop();
      }
      
      return ans;
   }
};
0
akbhobhiya4 weeks ago
class Solution{
public:
    int minValue(string s, int k){
        // code here
        vector<int>alfa(26,0);
        for(int i=0;i<s.length();i++)alfa[s[i]-'a']++;
        sort(alfa.begin(),alfa.end(),greater<int>());
        priority_queue<int>pq;
        for(int i=0;i<26;i++){
            if(alfa[i]>0)pq.push(alfa[i]);
            else break;
        }
        for(int i=0;i<k;i++){
            int top = pq.top();pq.pop();
            top--;
            pq.push(top);
        }
        int sum = 0;
        while(!pq.empty()){
            sum += pq.top()*pq.top();
            pq.pop();
        }
        return sum;
    }
};
0
harrypotter04 weeks ago
from collections import Counterimport heapqclass Solution:   def minValue(self, s, k):       d = Counter(s)       c = list(d.values())       # c.sort(reverse=True)       c = [i*-1 for i in c]       heapq.heapify(c)       while k>0:           temp = heapq.heappop(c)           temp +=1           heapq.heappush(c, temp)           k-=1       summ = 0       for i in c:           summ+=i**2       return summ 
0
jyoti2804mishra1 month ago
#JAVA SOLUTION
class Solution{   static int minValue(String s, int k){       // code here       Map<Character, Integer> map = new HashMap<>();              for(char c: s.toCharArray()) {           if (map.containsKey(c)) {               map.put(c, map.get(c)+1);           }else {               map.put(c, 1);           }       }       
       Queue<CharCount> queue = new PriorityQueue<>((a, b) -> b.count-a.count);              for (Map.Entry<Character, Integer> es:map.entrySet()) {           queue.offer(new CharCount(es.getKey(), es.getValue()));       }       while (!queue.isEmpty() && k-- > 0) {           CharCount c = queue.poll();           c.count--;           queue.offer(c);       }       
       int res = 0;       while (!queue.isEmpty()) {           int count = queue.poll().count;           res += count*count;       }              return res;                        }}
class CharCount {   char c;   int count;      CharCount(char c, int count) {       this.c = c;       this.count = count;   }      public String toString() {       return "char: "+c+" count: "+count;   }}
+1
shirurrohit1 month ago
PYTHON - O(26) Space
 
class Solution:
    def minValue(self, s, k):
        char_set = [0] * 26
        smallest_freq = float("inf")
        
        for i in s:
            char_set[ord(i)-97] += 1
        char_set.sort(reverse = True)
        
        i = 0
        while k:
            char_set[i] -= 1
            k -= 1
            bound = char_set[i]
            for j in range(26):
                if char_set[j] >= bound:
                    bound = char_set[j]
                    i = j
                    
        ans = 0        
        for i in char_set:
            if  i > 0:
                ans += i*i
        return ans
0
kiransaisk4481 month ago
Python Solution:
from collections import Counter
class Solution:
    def minValue(self, s, k):
        # code here
        d = Counter(s)
        c = list(d.values())
        c.sort(reverse=True)
        tot = 0
        max_ = c[0]
        i = 0
        while k > 0:
            c[i] -= 1
            k -= 1
            max_ = max(c)
            i = c.index(max_)
        for i in range(len(c)):
            tot = tot + c[i] ** 2
+2
rohanyt741 month ago
int minValue(string s, int k){       // code here       int sum=0;       priority_queue<int>pq;       unordered_map<char,int>um;       for(int i=0;i<s.length();i++){           um[s[i]]++;       }       for(auto x:um){           pq.push(x.second);       }       while(k){           int x=pq.top();           pq.pop();           x--;           pq.push(x);           k--;       }      while(!pq.empty()){          int d=pq.top();          sum=sum+(d*d);          pq.pop();      }      return sum;   }
0
himanshu201912 months ago
int minValue(string s, int k){       // code here       long long res=0;       int arr[26]={0};       int min=INT_MAX;       for(auto a:s){           arr[a-97]++;       }       priority_queue<int> p;       for(auto a:arr){           if(a!=0 && a<min) min=a;           if(a!=0) p.push(a);       }       while(k--){           int a=p.top();           a--;           p.pop();           if(a==0){               continue;           }           p.push(a);       }       while(p.empty()==false){           int val=p.top();           p.pop();           res+=val*val;       }       return res;   }
+1
aloksinghbais022 months ago
C++ solution having time complexity as O(N+26*log(26)+k*log(26)+26) and space complexity as O(26) is as follows :- 
 
Execution Time :- 0.0 / 1.1 sec
 
int minValue(string s, int k){       int freq[26] = {0};       for(int i = 0; i < s.length(); i++){           freq[s[i]-'a']++;       }              priority_queue<pair<int,int>> pq;       for(int i = 0; i < 26; i++){           if(freq[i]){               pq.push({freq[i],i});           }       }              while(!pq.empty() && k){           auto p = pq.top();           pq.pop();                      int f = p.first;           int i = p.second;                      freq[i]--;           f--;           k--;                      if(f){               pq.push({f,i});           }       }              int ans = 0;       for(int i = 0; i < 26; i++){           if(freq[i]){               ans += freq[i] * freq[i];           }       }              return (ans);   }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.