Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Game with String

Medium Acceptance 53.96% Points 30.00

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.

Examples
Example 1

image

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

Example 2

image

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

Hints
Hint 1
Expected Time Complexity: O(n+klog(p))
Hint 2
Expected Auxiliary Space: O(n)
Constraints
  • 0 <= k <= |string length| <= 5*10^4
Companies
Amazon Walmart Adobe
Topics
Heap
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions