Minimum Deletions for At Most K Distinct Characters - Problem

You are given a string s consisting of lowercase English letters, and an integer k. Your task is to delete some (possibly none) of the characters in the string so that the number of distinct characters in the resulting string is at most k.

Return the minimum number of deletions required to achieve this.

Example: If s = "aabbccdd" and k = 2, you need to keep at most 2 distinct characters. You could keep 'a' and 'b', deleting all 'c' and 'd' characters, requiring 4 deletions.

Input & Output

Example 1 — Basic Case
$ Input: s = "aabbccdd", k = 2
Output: 4
💡 Note: Keep 2 most frequent characters. All characters appear equally (2 times each), so we can keep any 2 characters like 'a' and 'b', deleting all 'c' and 'd' occurrences = 2 + 2 = 4 deletions.
Example 2 — Different Frequencies
$ Input: s = "aaabbc", k = 2
Output: 1
💡 Note: Character frequencies: a=3, b=2, c=1. Keep 'a' (3) and 'b' (2), delete 'c' (1). Total deletions = 1.
Example 3 — Edge Case
$ Input: s = "abc", k = 0
Output: 3
💡 Note: k=0 means we can keep 0 distinct characters, so we must delete all characters = 3 deletions.

Constraints

  • 1 ≤ s.length ≤ 105
  • s consists of lowercase English letters only
  • 0 ≤ k ≤ 26

Visualization

Tap to expand
Minimum Deletions for At Most K Distinct Characters INPUT String s = "aabbccdd" a a b b c c d d Character Frequencies: Char Count a 2 b 2 c 2 d 2 k = 2 distinct = 4 ALGORITHM STEPS 1 Count Frequencies Count each char occurrence 2 Sort by Frequency Ascending: [2,2,2,2] 3 Calculate Excess Need to remove: 4-2 = 2 chars 4 Remove Smallest First Delete 2 char types (greedy) Greedy Deletion: Remove 'a': 2 deletions Remove 'b': 2 deletions Total: 2 + 2 = 4 deletions FINAL RESULT Resulting String: "ccdd" c c d d Deleted Characters: a a b b OUTPUT 4 Verification: Distinct chars in "ccdd": 2 2 <= k(2) -- OK Key Insight: The greedy approach works because we want to minimize deletions. By sorting character frequencies in ascending order and removing the least frequent characters first, we achieve the minimum total deletions needed to reduce distinct characters to at most k. TutorialsPoint - Minimum Deletions for At Most K Distinct Characters | Greedy Optimization
Asked in
Google 45 Facebook 38 Amazon 32 Microsoft 28
23.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen