Skip to content

3085. Minimum Deletions to Make String K-Special 👍

  • Time: $O(n + 26^2) = O(n)$
  • Space: $O(26) = O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
 public:
  int minimumDeletions(string word, int k) {
    int ans = INT_MAX;
    vector<int> count(26);

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

    for (const int minFreq : count) {
      int deletions = 0;
      for (const int freq : count)
        if (freq < minFreq)  // Delete all the letters with smaller frequency.
          deletions += freq;
        else  // Delete letters with exceeding frequency.
          deletions += max(0, freq - (minFreq + k));
      ans = min(ans, deletions);
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
  public int minimumDeletions(String word, int k) {
    int ans = Integer.MAX_VALUE;
    int count[] = new int[26];

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

    for (final int minFreq : count) {
      int deletions = 0;
      for (final int freq : count)
        if (freq < minFreq) // Delete all the letters with smaller frequency.
          deletions += freq;
        else // Delete letters with exceeding frequency.
          deletions += Math.max(0, freq - (minFreq + k));
      ans = Math.min(ans, deletions);
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
  def minimumDeletions(self, word: str, k: int) -> int:
    ans = math.inf
    count = collections.Counter(word)

    for minFreq in count.values():
      deletions = 0
      for freq in count.values():
        if freq < minFreq:
          deletions += freq
        else:
          deletions += max(0, freq - (minFreq + k))
      ans = min(ans, deletions)

    return ans