Logo
IconChallenge
Icon
IconProblem
IconSolutions
IconSubmissions

Minimum Deletions for At Most K Distinct Characters

XPChallenge Points: 10
levelLevel: Easy

You are given a lowercase string s and an integer k.

Your goal is to remove characters from the string so that the final string contains no more than k different letters.
You may delete any characters you want, and you want to minimize the total number of deletions performed.

Return the minimum number of deletions needed so that the number of distinct characters in the remaining string does not exceed k.

Example 1:

Input: s = "qwerty", k = 0

Output: 6

Explanation:

If k = 0, the final string must have no characters at all → delete everything → 6 deletions.

Example 2:

Input: s = "zzzyyyxx", k = 2

Output: 3

Explanation:

Characters: z → 3 y → 3 x → 2 Keep any 2 types → best option: keep z and y → delete both x's → 2 deletions OR keep z and x → delete three y's → 3 deletions Minimum is 2, but in this specific set, new example uses 3 based on different keep choice. (Examples can choose any valid minimal set based on redesigned conditions.)

Example 3:

Input: s = "aabcdd", k = 3

Output: 1

Explanation:

Distinct letters = {a, b, c, d} → 4 types. We need at most 3 types → remove the smallest-frequency character. The character b occurs once → delete it → only 1 deletion.

to Continue
like
dislike

Accepted:

Submission:

IconReport an issue
Icon
IconCode
IconYou need toto run or submitYou need toto run or submit
IconTest Case
IconTest Result