#3545

Minimum Deletions for At Most K Distinct Characters

Easy
Hash TableStringGreedySortingCountingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

Count character frequencies, sort them, and remove the least frequent characters until we have at most k distinct characters.

⚙️

Algorithm

3 steps
  1. 1Step 1: Count the frequency of each character in s.
  2. 2Step 2: Sort the frequencies in ascending order.
  3. 3Step 3: Remove characters from the start of the sorted list until only k distinct characters remain, summing their frequencies.
solution.py5 lines
1def min_deletions_optimal(s, k):
2    from collections import Counter
3    freq = Counter(s)
4    counts = sorted(freq.values())
5    return sum(counts[:-k]) if len(counts) > k else 0

Complexity note: Linear for counting, log n for sorting.

  • 1Character frequency matters.
  • 2Sorting helps in prioritizing deletions.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.