LeetCode 1647. Minimum Deletions to Make Character Frequencies Unique Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
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 <= 105
  • s contains only lowercase English letters.

Solutions

Solution 1: Array + Sorting

First, we use an array cnt of length 26 to count the occurrences of each letter in the string s.

Then, we sort the array cnt in descending order. We define a variable pre to record the current number of occurrences of the letter.

Next, we traverse each element v in the array cnt. If the current pre is 0, we directly add v to the answer. Otherwise, if v ≥ pre, we add v - pre + 1 to the answer and decrement pre by 1. Otherwise, we directly update pre to v. Then, we continue to the next element.

After traversing, we return the answer.

The time complexity is O(n + |Σ| × log |Σ|), and the space complexity is O(|Σ|). Here, n is the length of the string s, and |Σ| is the size of the alphabet. In this problem, |Σ| = 26.

PythonJavaC++GoTypeScriptRust
class Solution: def minDeletions(self, s: str) -> int: cnt = Counter(s) ans, pre = 0, inf for v in sorted(cnt.values(), reverse=True): if pre == 0: ans += v elif v >= pre: ans += v - pre + 1 pre -= 1 else: pre = v return ans(code-box)

Solution 2

PythonJavaC++Go
class Solution: def minDeletions(self, s: str) -> int: cnt = Counter(s) vals = sorted(cnt.values(), reverse=True) ans = 0 for i in range(1, len(vals)): while vals[i] >= vals[i - 1] and vals[i] > 0: vals[i] -= 1 ans += 1 return ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !