Minimum Deletions to Make Character Frequencies Unique Problem
Description
LeetCode Problem 1647.
A string s is called good if there are no two different characters in s that have the same frequency.
Given a string s, return the minimum number of characters you need to delete to make s good.
The frequency of a character in a string is the number of times it appears in the string. For example, in the string "aab", the frequency of 'a' is 2, while the frequency of 'b' is 1.
Example 1:
Input: s = "aab"
Output: 0
Explanation: s is already good.
Example 2:
Input: s = "aaabbbcc"
Output: 2
Explanation: You can delete two 'b's resulting in the good string "aaabcc".
Another way it to delete one 'b' and one 'c' resulting in the good string "aaabbc".
Example 3:
Input: s = "ceabaacb"
Output: 2
Explanation: You can delete both 'c's resulting in the good string "eabaab".
Note that we only care about characters that are still in the string at the end (i.e. frequency of 0 is ignored).
Constraints:
1 <= s.length <= 10^5scontains only lowercase English letters.
Solution
Approach: Greedy on Sorted Frequencies
Only the frequencies matter, not which letters they belong to, and deleting can only lower a frequency. Count the frequency of each letter and handle them from the largest down.
Keep allowed, the largest frequency that is still free. The largest frequency can stay as it is. For each next one, c:
- keep
min(c, allowed)copies of the letter and delete the rest; - the next letter must then stay strictly below what this one kept, so
allowedbecomeskeep - 1(but not below0).
Frequency 0 means the letter is gone entirely, and any number of letters can be gone, so once allowed reaches 0, every remaining letter is deleted completely. For "aaabbbcc" the frequencies are 3, 3, 2: keep 3, cut the second 3 down to 2, then cut the 2 down to 1, for 2 deletions.
Lowering each frequency only to the largest free value is optimal: going lower would only cost more deletions, and it would leave less room for the frequencies that come after.
Complexity: O(n) time to count, plus sorting 26 numbers. O(1) extra space.
from collections import Counter
class Solution:
def minDeletions(self, s: str) -> int:
ans = 0
allowed = len(s) # the largest frequency still free
for c in sorted(Counter(s).values(), reverse=True):
keep = min(c, allowed) # cut this letter down to the largest free frequency
ans += c - keep
allowed = max(keep - 1, 0) # frequency 0 (letter gone) may repeat
return ans