Skip to content

1647. Minimum Deletions to Make Character Frequencies Unique 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  int minDeletions(string s) {
    int ans = 0;
    vector<int> count(26);
    unordered_set<int> usedFreq;

    for (const char c : s)
      ++count[c - 'a'];

    for (int freq : count)
      while (freq > 0 && !usedFreq.insert(freq).second) {
        --freq;  // Delete ('a' + i).
        ++ans;
      }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
  public int minDeletions(String s) {
    int ans = 0;
    int[] count = new int[26];
    Set<Integer> usedFreq = new HashSet<>();

    for (final char c : s.toCharArray())
      ++count[c - 'a'];

    for (int freq : count) {
      while (freq > 0 && usedFreq.contains(freq)) {
        --freq; // Delete ('a' + i).
        ++ans;
      }
      usedFreq.add(freq);
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
  def minDeletions(self, s: str) -> int:
    ans = 0
    count = collections.Counter(s)
    usedFreq = set()

    for freq in count.values():
      while freq > 0 and freq in usedFreq:
        freq -= 1  # Delete ('a' + i).
        ans += 1
      usedFreq.add(freq)

    return ans