[LeetCode] Minimum Deletions to Make Character Frequencies Unique

1647. Minimum Deletions to Make Character Frequencies Unique

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
bool possible(int count[26], int target) {
for(int i = 0; i < target; i++) {
if(count[i] == count[target]) return false;
}
return true;
}
public:
int minDeletions(string s) {
int count[26]{};
int res = 0;
for(auto c : s) count[c - 'a']++;
for(int i = 0; i < 26; i++) {
while(count[i] && !possible(count, i)) count[i]--, res++;
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/06/26/PS/LeetCode/minimum-deletions-to-make-character-frequencies-unique/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.