3871. Minimum Deletions for At Most K Distinct Characters
My accepted Python solution to LeetCode problem 3871, Minimum Deletions for At Most K Distinct Characters, running in 3ms.
- Difficulty: Easy
- Python
- Runtime 3ms
- Memory 17.5MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
Python
Accepted on LeetCode — runtime 3ms, memory 17.5MB, accepted 2026-01-02.
class Solution:
def minDeletion(self, s: str, k: int) -> int:
from collections import Counter
freq = Counter(s)
if len(freq) <= k:
return 0
# Need to remove all occurrences of (len(freq) - k) characters
# Choose the ones with smallest frequencies
freqs = sorted(freq.values())
to_remove = len(freq) - k
return sum(freqs[:to_remove])