↓Skip to main content
  1. LeetCode/

LeetCode 3545: Minimum Deletions for At Most K Distinct Characters

·1 min· ·
LeetCode Easy Greedy Hash-Table String Sorting Counting
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2025-05-11

  • Submissions: Accepted (first try)

Approach
#

Deleting only part of a character’s occurrences does not reduce the number of kinds, so delete whole kinds. With m kinds and at most k allowed, delete m - k kinds, choosing the least frequent ones to minimize deleted characters.

My Solution
#

class Solution:
    def minDeletion(self, s: str, k: int) -> int:
        freq = sorted(Counter(s).values())
        drop = max(0, len(freq) - k)
        return sum(freq[:drop])

I originally sorted the Counter into a dict by count and counted up to len - k entries; sorting values() is enough.

Complexity
#

Time O(n + σ log σ) with σ kinds (at most 26), space O(σ).

Mistakes to Avoid
#

  • When there are already <= k kinds, len(freq) - k is negative, and freq[:negative] slices from the end; clamp with max(0, ...).

Interview Explanation
#

Partial deletion never reduces the kinds, so only whole kinds can go. I count each character, sort the counts ascending, and delete the m - k smallest kinds, summing their counts. Time O(n).

Related

LeetCode 3541: Find Most Frequent Vowel and Consonant
·1 min
LeetCode Easy Hash-Table String Counting
LeetCode 3541 note: count characters, take the maximum among vowels and among consonants and add them; a missing class counts as 0
LeetCode 1160: Find Words That Can Be Formed by Characters
·1 min
LeetCode Easy Array Hash-Table String Counting
LeetCode 1160 note: a word is formable when none of its character counts exceeds chars’; sum the lengths of such words
LeetCode 2357: Make Array Zero by Subtracting Equal Amounts
·1 min
LeetCode Easy Array Hash-Table Greedy Sorting
LeetCode 2357 note: each operation zeroes the group of the smallest positive value, so the answer is the number of distinct positive values
LeetCode 1189: Maximum Number of Balloons
·2 mins
LeetCode Easy Hash-Table String Counting
LeetCode 1189 note: each letter supports count // needed balloons, with l and o needed twice; take the minimum
LeetCode 884: Uncommon Words from Two Sentences
·1 min
LeetCode Easy Hash-Table String Counting
LeetCode 884 note: count words across both sentences together; those appearing exactly once are the answer
LeetCode 819: Most Common Word
·2 mins
LeetCode Easy Array Hash-Table String Counting
LeetCode 819 note: replace punctuation with spaces, lowercase, split, count, and pick the most frequent word not banned