Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit ea5a475

Browse files
authored
Create Minimum Deletions to Make String K-Special.py
1 parent 2f65ab4 commit ea5a475

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
'''
2+
You are given a string word and an integer k.
3+
4+
We consider word to be k-special if |freq(word[i]) - freq(word[j])| <= k for all indices i and j in the string.
5+
6+
Here, freq(x) denotes the frequency of the character x in word, and |y| denotes the absolute value of y.
7+
8+
Return the minimum number of characters you need to delete to make word k-special.
9+
'''
10+
class Solution:
11+
def minimumDeletions(self, word: str, k: int) -> int:
12+
freqMap = defaultdict(int)
13+
for c in word:
14+
freqMap[c] += 1
15+
16+
frequencies = sorted(freqMap.values())
17+
minDeletions = float('inf')
18+
n = len(frequencies)
19+
20+
for i in range(n):
21+
base = frequencies[i]
22+
totalDeletions = 0
23+
24+
for j in range(i):
25+
totalDeletions += frequencies[j]
26+
27+
for j in range(i, n):
28+
if frequencies[j] > base + k:
29+
totalDeletions += frequencies[j] - (base + k)
30+
31+
if totalDeletions < minDeletions:
32+
minDeletions = totalDeletions
33+
34+
return minDeletions
35+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /