1647. Minimum Deletions to Make Character Frequencies Unique
Description
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.
Example 1:
Input: s = "aab" Output: 0 Explanation: s is already good.
Example 2:
Input: s = "aaabbbcc" Output: 2 Explanation: You can delete two 'b's resulting in the good string "aaabcc". Another way it to delete one 'b' and one 'c' resulting in the good string "aaabbc".
Example 3:
Input: s = "ceabaacb" Output: 2 Explanation: You can delete both 'c's resulting in the good string "eabaab". Note that we only care about characters that are still in the string at the end (i.e. frequency of 0 is ignored).
Constraints:
1 <= s.length <= 105scontains only lowercase English letters.
Solutions
Solution 1: Array + Sorting
First, we use an array \(\textit{cnt}\) of length \(26\) to count the occurrences of each letter in the string \(s\).
Then, we sort the array \(\textit{cnt}\) in descending order. We define a variable \(\textit{pre}\) to record the current number of occurrences of the letter.
Next, we traverse each element \(v\) in the array \(\textit{cnt}\). If the current \(\textit{pre}\) is \(0\), we directly add \(v\) to the answer. Otherwise, if \(v \geq \textit{pre}\), we add \(v - \textit{pre} + 1\) to the answer and decrement \(\textit{pre}\) by \(1\). Otherwise, we directly update \(\textit{pre}\) to \(v\). Then, we continue to the next element.
After traversing, we return the answer.
The time complexity is \(O(n + |\Sigma| \times \log |\Sigma|)\), and the space complexity is \(O(|\Sigma|)\). Here, \(n\) is the length of the string \(s\), and \(|\Sigma|\) is the size of the alphabet. In this problem, \(|\Sigma| = 26\).
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
Solution 2
1 2 3 4 5 6 7 8 9 10 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |