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(n)
Input : str = abccc, K = 1 Output : 6 We remove c to get the value as 12 + 12 + 22 Input : str = aaab, K = 2 Output : 2
Asked In : Amazon
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.
Below is the implementation of the above idea.
Time Complexity: O(n)
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Character replacement after removing duplicates from a string
- Minimize the length of string by removing occurrence of only one character
- Lexicographically smallest string formed by removing at most one character
- Ways of transforming one string to other by removing 0 or more characters
- Reduce the string by removing K consecutive identical characters
- Lexicographically smallest string formed by appending a character from the first K characters of a given string
- Lexicographically smallest string formed by appending a character from first K characters of a string | Set 2
- Maximum number of characters between any two same character in a string
- Character whose frequency is equal to the sum of frequencies of other characters of the given string
- Find the character made by adding all the characters of the given string
- Find the character in first string that is present at minimum index in second string
- Minimum deletions from string to reduce it to string with at most 2 unique characters
- Minimum characters to be added at front to make string palindrome
- Minimum length String with Sum of the alphabetical values of the characters equal to N
- Minimum number of characters to be removed to make a binary string alternate