Minimum Deletions to Make String K-Special - Problem

You are given a string word and an integer k. We consider word to be k-special if |freq(word[i]) - freq(word[j])| <= k for all indices i and j in the string.

Here, freq(x) denotes the frequency of the character x in word, and |y| denotes the absolute value of y.

Return the minimum number of characters you need to delete to make word k-special.

Input & Output

Example 1 — Basic Case
$ Input: word = "aab", k = 0
Output: 1
💡 Note: Character frequencies: a=2, b=1. Since |2-1|=1 > 0, we need deletions. We can keep all characters of one type. Keeping 'a' (2 chars) requires deleting 1 'b'. Keeping 'b' (1 char) requires deleting 2 'a's. Minimum deletions = 1.
Example 2 — K-Special Already
$ Input: word = "aabbcc", k = 1
Output: 0
💡 Note: Character frequencies: a=2, b=2, c=2. All differences are |2-2|=0 ≤ 1, so string is already k-special. No deletions needed.
Example 3 — Larger K
$ Input: word = "aaabbbccc", k = 2
Output: 0
💡 Note: Character frequencies: a=3, b=3, c=3. All differences are 0 ≤ 2, so no deletions needed.

Constraints

  • 1 ≤ word.length ≤ 105
  • 0 ≤ k ≤ 26
  • word consists only of lowercase English letters

Visualization

Tap to expand
Minimum Deletions to Make String K-Special INPUT String: "aab" a a b Frequency Count: a: 2 b: 1 word = "aab" k = 0 frequencies: [2, 1] K-special condition: |freq(i) - freq(j)| <= k |2 - 1| = 1 > 0 (FAIL) ALGORITHM STEPS 1 Count Frequencies freq(a)=2, freq(b)=1 2 Sort Frequencies sorted: [1, 2] 3 Sliding Window Try each min freq Option A: Keep all 'a' (freq=2) Delete 'b': 1 deletion Option B: Keep all 'b' (freq=1) Delete 'aa': 2 deletions But max diff must be 0! 4 Find Minimum k=0: all same freq Keep 1 char: del 2 FINAL RESULT Original: "aab" a a b Result: "b" b freq(b) = 1 All frequencies equal! |1 - 1| = 0 <= 0 (OK) Output: 2 Key Insight: With k=0, all remaining characters must have EQUAL frequency. We try keeping each unique frequency as target and calculate deletions. The greedy sliding window approach efficiently finds the minimum deletions by considering optimal ranges of frequencies to keep. TutorialsPoint - Minimum Deletions to Make String K-Special | Optimized Greedy with Sliding Window
Asked in
Meta 12 Google 8 Amazon 6 Microsoft 4
3.2K Views
Medium Frequency
~25 min Avg. Time
147 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