Given a string str consisting of lowercase alphabets and a number k, the task is to find the minimum possible value of the string after removing k characters. The value of a string is defined as the sum of the squares of the frequencies of each distinct character in the string. Your goal is to return the minimum value that can be achieved after removing exactly k characters.

Input: str = aabbbbcc, k = 2
Output: 12
Explanation: We remove two 'b's from the string to get the updated string "aabcc". The value is calculated as: 'a' occurs 2 times ? 22 = 4. 'b' occurs 2 times ? 22 = 4. 'c' occurs 2 times ? 2^2 = 4. Total value = 4 + 4 + 4 = 12

Input: str = abc, k = 1
Output: 2
Explanation: We remove one character (e.g., 'a') to get the updated string "bc". The value is calculated as: 'b' occurs 1 time ? 12 = 1. 'c' occurs 1 time ? 12 = 1. Total value = 1 + 1 = 2
Approach, complexity and clean code in every language. Sign in to unlock the editorial.
Your submissions, results and runtime history live here. Sign in to start your streak.
aabbbbcc 2
12
abc 1
2
xxxxxxyyyyyyzzzzzzxxxxxxyyyyyyzzzzzzxxxxxxyyyyyyzzzzzz 15
507