Given a string 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. For example consider the string “saideep”, here frequencies of characters are s-1, a-1, i-1, e-2, d-1, p-1 and value of the string is 1^2 + 1^2 + 1^2 + 1^2 + 1^2 + 2^2 = 9. Expected Time Complexity: O(k*logn)
Input : str = abccc, K = 1 Output : 6 Explanation: We remove c to get the value as 12 + 12 + 22
One clear observation is that we need to remove character with highest frequency. One trick is the character ma A Simple solution is to use sorting technique through all current highest frequency reduce up to k times. For After every reduce again sort frequency array.
A Better Solution used to Priority Queue which has to the highest element on top.
Initialize empty priority queue.
Count frequency of each character and Store into temp array.
Remove K characters which have highest frequency from queue.
Finally Count Sum of square of each element and return it.
Time Complexity:O(k*logn) Auxiliary Space: O(N) because constant size array but priority_queue is storing characters almost the length of the string in worst case.
Efficient Approach :
We can solve it in O(N) time complexity as we need to be greedy and always remove the characters of alphabets which are higher in frequency.
Example: Let str=”abbccc” and k=2 now, alphabetCount=1;//for ‘a’ alphabetCount=2;//for ‘b’ alphabetCount=3;//for ‘c’ maximum=3 m=1(only a occur 1 times) m=1(only b occur 2 times) m=1(only c occur 3 times) //k=2 maximum=3 so k=k-m[maximum]//k=k-1; so now one c got removes so frequencies are a=1,b=2,c=2; so as c’s frequency got decreased by one m[maximum] will be zero and m[maximum-1] will be increased by m[maximum] so update m+=m, m=0; also maximum gets decreased by one as it is guaranteed to exist frequency one less than maximum from above. m=1 , m=2 , m=0 and k=1; now m[maximum](i.e m=2>k) so we should partially remove remove one character of either b or c so m=2 0,m=1 ,m=0 and k=0; so, (1*1)*2 + (2*2)*1 + (3*3)*0 = 6//ans
// C++ program to find min sum of squares
// of characters after k removals
constintMAX_CHAR = 26;
// Main Function to calculate min sum of
// squares of characters after k removals
intminStringValue(string str, intk)
// Here the array stored frequency the number of
// occurrences in string m[frequency]=number of alphabets
// with frequency i.e, in our example abbccc m=1(1
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Login to comment...