Skip to content

Commit 1a47ab4

Browse files
authored
Create minimum-deletions-to-make-string-k-special.py
1 parent 54c052c commit 1a47ab4

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
# Time: O(n + 26)
2+
# Space: O(n + 26)
3+
4+
# freq table, counting sort, two pointers
5+
class Solution(object):
6+
def minimumDeletions(self, word, k):
7+
"""
8+
:type word: str
9+
:type k: int
10+
:rtype: int
11+
"""
12+
def counting_sort(arr, key=lambda x:x, reverse=False): # Time: O(n), Space: O(n)
13+
count = [0]*(max(arr, key=key)+1)
14+
for x in arr:
15+
count[key(x)] += 1
16+
for i in xrange(1, len(count)):
17+
count[i] += count[i-1]
18+
result = [0]*len(arr)
19+
if not reverse:
20+
for x in reversed(arr): # stable sort
21+
count[key(x)] -= 1
22+
result[count[key(x)]] = x
23+
else:
24+
for x in arr: # stable sort
25+
count[key(x)] -= 1
26+
result[count[key(x)]] = x
27+
result.reverse()
28+
return result
29+
30+
cnt = [0]*26
31+
for x in word:
32+
cnt[ord(x)-ord('a')] += 1
33+
arr = counting_sort([x for x in cnt if x])
34+
result = float("inf")
35+
right = prefix = 0
36+
suffix = len(word)
37+
prev = -1
38+
for left in xrange(len(arr)):
39+
if left+1 < len(arr) and arr[left+1] == arr[left]:
40+
continue
41+
while right < len(arr) and arr[right] <= arr[left]+k:
42+
suffix -= arr[right]
43+
right += 1
44+
result = min(result, prefix+(suffix-(arr[left]+k)*(len(arr)-right)))
45+
prefix += arr[left]*(left-prev)
46+
prev = left
47+
return result
48+
49+
50+
# Time: O(n + 26^2)
51+
# Space: O(26)
52+
# freq table
53+
class Solution2(object):
54+
def minimumDeletions(self, word, k):
55+
"""
56+
:type word: str
57+
:type k: int
58+
:rtype: int
59+
"""
60+
cnt = [0]*26
61+
for x in word:
62+
cnt[ord(x)-ord('a')] += 1
63+
return min(sum(y if y < x else max(y-(x+k), 0) for y in cnt if y) for x in cnt if x)

0 commit comments

Comments
 (0)