Practice › Strings
Minimum Deletions for Unique Letter Counts
Medium · Strings · Asked at Microsoft, Amazon, Google
A string is good if no two different letters occur the same number of times. Print the minimum number of characters to delete from s to make it good. (A letter deleted completely no longer counts.)
Input
A single line with the string (lowercase letters).
Output
The minimum number of deletions.
Constraints
- 1 ≤ length ≤ 10^5
Sort the 26 counts in decreasing order. Each next count may be at most one less than the previous kept count (and not below 0); delete whatever is above that limit.
Example 1
Input
aab
Output
0
Example 2
Input
aaabbbcc
Output
2
Hints
- Only the 26 counts matter, not where the letters are.
- Process the counts from largest to smallest.
- Each count must be strictly smaller than the previous kept count (or become 0).
Approach
Sort the counts in decreasing order. Keep a limit, initially unbounded. For each count c > 0: keep = max(0, min(c, limit)); add c − keep to the deletions and set limit = keep − 1. Lowering the larger counts first would only cost more, so this greedy is optimal.
Complexity: O(n + 26 log 26) time · O(26) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
string s;
cin >> s;
vector<long long> c(26, 0);
for (char ch : s) c[ch - 'a']++;
sort(c.rbegin(), c.rend());
long long del = 0, limit = LLONG_MAX;
for (long long x : c) {
if (x == 0) break;
long long keep = max(0LL, min(x, limit));
del += x - keep;
limit = keep - 1;
}
cout << del << "\n";
return 0;
}Python solution
from collections import Counter
s = input().strip()
counts = sorted(Counter(s).values(), reverse=True)
deletions = 0
limit = float("inf")
for x in counts:
keep = max(0, min(x, limit))
deletions += x - keep
limit = keep - 1
print(deletions)Java solution
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
String s = new BufferedReader(new InputStreamReader(System.in)).readLine().trim();
Integer[] c = new Integer[26];
Arrays.fill(c, 0);
for (char ch : s.toCharArray()) c[ch - 'a']++;
Arrays.sort(c, Collections.reverseOrder());
long del = 0, limit = Long.MAX_VALUE;
for (int x : c) {
if (x == 0) break;
long keep = Math.max(0, Math.min(x, limit));
del += x - keep;
limit = keep - 1;
}
System.out.println(del);
}
}Solve Minimum Deletions for Unique Letter Counts online · All practice problems