Minimum Deletions to Make String K-Special - Problem
Minimum Deletions to Make String K-Special

You are given a string word and an integer k. Your goal is to make the string k-special by deleting the minimum number of characters.

A string is considered k-special if the absolute difference between any two character frequencies is at most k. In other words, for any two characters in the string, |freq(char1) - freq(char2)| ≤ k.

Key Points:
freq(x) represents how many times character x appears in the string
• You need to find the minimum number of deletions required
• After deletions, all remaining character frequencies must be within k of each other

Example: If word = "aabccc" and k = 2, the frequencies are: a=2, b=1, c=3. The maximum difference is |3-1|=2, which equals k, so no deletions needed!

Input & Output

example_1.py — Basic Case
$ Input: word = "aabccc", k = 2
Output: 0
💡 Note: Character frequencies are: a=2, b=1, c=3. The maximum difference is |3-1| = 2, which equals k. No deletions needed.
example_2.py — Need Deletions
$ Input: word = "aabcccdd", k = 1
Output: 2
💡 Note: Frequencies: a=2, b=1, c=3, d=2. Max difference is |3-1| = 2 > k. Delete 2 'c's to get frequencies [2,1,1,2], max diff = 1 ≤ k.
example_3.py — All Same Character
$ Input: word = "aaaa", k = 0
Output: 0
💡 Note: Only one unique character 'a' with frequency 4. Since there's only one frequency, the difference is 0 ≤ k. No deletions needed.

Time & Space Complexity

Time Complexity
⏱️
O(n + c log c)

O(n) to count frequencies, O(c log c) to sort where c ≤ 26 is unique characters

n
2n
Linearithmic
Space Complexity
O(c)

Space to store character frequencies, where c ≤ 26

n
2n
Linear Space

Constraints

  • 1 ≤ word.length ≤ 105
  • word consists of lowercase English letters only
  • 0 ≤ k ≤ 26
  • Time limit: 2 seconds
Asked in
25.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen