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: Keep At Most k=2 Distinct CharactersInput String:aabbccdd"aabbccdd" - 4 distinct charactersCharacter Frequencies:a: 2b: 2c: 2d: 2KeepKeepDeleteDeleteKeep k=2 charactersDelete remaining: 2+2=4Result: Minimum 4 deletions neededFinal string could be "aabb" with only 2 distinct characters
Understanding the Visualization
1
Input
String s="aabbccdd" with k=2 distinct characters allowed
2
Process
Count frequencies and keep k most frequent characters
3
Output
Minimum deletions needed = 4
Key Takeaway
🎯 Key Insight: To minimize deletions, always keep the k characters that appear most frequently in the string
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