Minimum Deletions to Make Character Frequencies Unique (LeetCode 1647): Solution and Explanation
Delete as few characters as possible from s so that no two letters that remain appear the same number of times.
Intuition
Positions do not matter, only how many times each letter appears. The task is to lower some of those counts until they are all different, with the smallest total amount lowered.
Go from the most frequent letter to the least. The first letter keeps its full count. Each next letter must land strictly below the count just kept, so there is a ceiling that falls as we go.
Cutting a count down exactly to the ceiling is the cheapest legal choice, and it also leaves the highest possible ceiling for the letters after it. Once the ceiling hits 0, any remaining letter must be deleted entirely.
Approach: Sorted counts and a falling ceiling
- Count each letter and sort the counts in decreasing order.
- Set
deletions = 0andallowed = len(s). - For each count
f:keep = min(f, allowed), addf - keeptodeletions, then setallowed = max(keep - 1, 0). - Return
deletions.
Step-by-step example
s = "aaabbbcc"
- Counts: a = 3, b = 3, c = 2. Sorted: 3, 3, 2.
- a: keep min(3, 8) = 3. No deletions. Ceiling drops to 2.
- b: count 3 is above the ceiling 2. Keep 2, delete 1. deletions = 1. Ceiling drops to 1.
- c: count 2 is above the ceiling 1. Keep 1, delete 1. deletions = 2. Ceiling drops to 0.
- Return 2.
Code: Python, Java, C++
1class Solution:
2 def minDeletions(self, s: str) -> int:
3 freqs = sorted(Counter(s).values(), reverse=True)
4 deletions = 0
5 allowed = len(s)
6 for f in freqs:
7 keep = min(f, allowed)
8 deletions += f - keep
9 allowed = max(keep - 1, 0)
10 return deletions1class Solution {
2 public int minDeletions(String s) {
3 int[] freq = new int[26];
4 for (char c : s.toCharArray()) freq[c - 'a']++;
5 Arrays.sort(freq);
6 int deletions = 0;
7 int allowed = s.length();
8 for (int i = 25; i >= 0; i--) {
9 int keep = Math.min(freq[i], allowed);
10 deletions += freq[i] - keep;
11 allowed = Math.max(keep - 1, 0);
12 }
13 return deletions;
14 }
15}1class Solution {
2public:
3 int minDeletions(string s) {
4 vector<int> freq(26, 0);
5 for (char c : s) freq[c - 'a']++;
6 sort(freq.rbegin(), freq.rend());
7 int deletions = 0;
8 int allowed = s.size();
9 for (int f : freq) {
10 int keep = min(f, allowed);
11 deletions += f - keep;
12 allowed = max(keep - 1, 0);
13 }
14 return deletions;
15 }
16};Time and space complexity
O(n)
Counting takes O(n). There are at most 26 counts, so sorting and the loop are constant time.
O(1)
At most 26 counts are stored.
Other approaches
Set of used frequencies (time O(n + 26^2) in the worst case, space O(26))
Process letters in any order. For each count, decrement it while it is positive and already in a used set, counting each decrement, then add the final count to the set. Simple but can take more steps per letter.
Max-heap (time O(n + 26 log 26 * n) worst case, space O(26))
Push all counts into a max-heap. Pop the largest; if it equals the next top, decrement it, count a deletion and push it back if still positive. Same idea as sorting, driven by the heap.
Common mistakes
- Letting the ceiling go negative. Once it reaches 0, the remaining letters are deleted completely, and the ceiling stays at 0.
- Lowering a duplicate count by only one. It may land on another count that is already taken, so it must drop below the previous kept count.
- Treating frequency 0 as a collision. Fully deleted letters do not count, so several letters can all end at 0.
- Sorting ascending and pushing counts up. Counts can only go down because we only delete.
Frequently asked questions
Why process counts from largest to smallest?
The largest count never needs cutting if it goes first, and every smaller count only has to stay under the ones before it. Going in this order lets one ceiling variable capture all the constraints.
Is cutting to exactly the ceiling always optimal?
Yes. Any lower value costs more deletions now and gives a lower ceiling to later letters, which can only cost more later.
Why start the ceiling at len(s)?
No count can exceed the string length, so the first letter is never cut. Any value at least as large as the biggest count works.