3085. Minimum Deletions to Make String K-Special
You are given a string
wordand an integerk.We consider
wordto be k-special if|freq(word[i]) - freq(word[j])| <= kfor all indicesiandjin the string.Here,
freq(x)denotes the frequency of the characterxinword, and|y|denotes the absolute value ofy.Return the minimum number of characters you need to delete to make
wordk-special.Example 1:
Input: word = "aabcaba", k = 0
Output: 3
Explanation: We can make
word0-special by deleting2occurrences of"a"and1occurrence of"c". Therefore,wordbecomes equal to"baba"wherefreq('a') == freq('b') == 2.Example 2:
Input: word = "dabdcbdcdcd", k = 2
Output: 2
Explanation: We can make
word2-special by deleting1occurrence of"a"and1occurrence of"d". Therefore,wordbecomes equal to "bdcbdcdcd" wherefreq('b') == 2,freq('c') == 3, andfreq('d') == 4.Example 3:
Input: word = "aaabaaa", k = 2
Output: 1
Explanation: We can make
word2-special by deleting1occurrence of"b". Therefore,wordbecomes equal to"aaaaaa"where each letter's frequency is now uniformly6.
def minimumDeletions(self, word: str, k: int) -> int:
freq = {}
for i in word:
if i in freq:
freq[i] += 1
else:
freq[i] = 1
res = len(word)
for a in freq.values():
deleted = 0
for b in freq.values():
if a > b:
deleted += b
elif b > a + k:
deleted += b - (a + k)
res = min(res, deleted)
return res