#1647
Medium Algorithms Minimum deletions to make character frequencies unique
Hash Table String Greedy Sorting
61.4% acceptance
Feb 25, 2026
5051
76
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.
Solution
Rust
Time O(n²)
Space O(n)
use std::collections::HashSet;
impl Solution {
pub fn min_deletions(s: String) -> i32 {
let mut freq = [0i32; 26];
for b in s.bytes() {
freq[(b - b'a') as usize] += 1;
}
let mut freq: Vec<i32> = freq.into_iter().filter(|&f| f > 0).collect();
freq.sort_unstable_by(|a, b| b.cmp(a));
let mut used: HashSet<i32> = HashSet::new();
let mut deletions = 0;
for mut f in freq {
while f > 0 && used.contains(&f) {
f -= 1;
deletions += 1;
}
if f > 0 {
used.insert(f);
}
}
deletions
}
}