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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code