Minimum Deletions to Make Character Frequencies Unique

medium string hash map greedy

Problem

Given a string s, return the minimum number of characters to delete so that the frequencies of all remaining characters are pairwise distinct.

Inputs = "aaabbbcc"
Output2
Counts {a:3, b:3, c:2} — drop one b and one c to get {3, 2, 1}.

from collections import Counter

def min_deletions(s):
    counts = sorted(Counter(s).values(), reverse=True)
    used = set()
    dels = 0
    for f in counts:
        while f > 0 and f in used:
            f -= 1
            dels += 1
        if f > 0: used.add(f)
    return dels
function minDeletions(s) {
  const c = new Map();
  for (const ch of s) c.set(ch, (c.get(ch) || 0) + 1);
  const counts = [...c.values()].sort((a, b) => b - a);
  const used = new Set();
  let dels = 0;
  for (let f of counts) {
    while (f > 0 && used.has(f)) { f--; dels++; }
    if (f > 0) used.add(f);
  }
  return dels;
}
class Solution {
    public int minDeletions(String s) {
        int[] c = new int[26];
        for (char ch : s.toCharArray()) c[ch - 'a']++;
        Set<Integer> used = new HashSet<>();
        int dels = 0;
        for (int f : c) {
            while (f > 0 && used.contains(f)) { f--; dels++; }
            if (f > 0) used.add(f);
        }
        return dels;
    }
}
int minDeletions(string s) {
    int c[26] = {0};
    for (char ch : s) c[ch - 'a']++;
    unordered_set<int> used;
    int dels = 0;
    for (int f : c) {
        while (f > 0 && used.count(f)) { f--; dels++; }
        if (f > 0) used.insert(f);
    }
    return dels;
}
Time: O(n + Σ²) Space: O(Σ)