1756 Minimum Deletions To Make String Balanced
1756 Minimum Deletions To Make String Balanced
Minimum Deletions to Make String Balanced 
You are given a string s consisting only of characters ‘a’ and ‘b’.
You can delete any number of characters in s to make s balanced. s is balanced if there is no pair of indices (i,j) such that i < j and s[i] = ‘b’ and s[j]= ‘a’.
Return the minimum number of deletions needed to make *s balanced*.
Example 1:
1
2
3
4
5
6
7
**Input:** s = "aababbab"
**Output:** 2
**Explanation:** You can either:
Delete the characters at 0-indexed positions 2 and 6 ("aababbab" -> "aaabbb"), or
Delete the characters at 0-indexed positions 3 and 6 ("aababbab" -> "aabbbb").
Example 2:
1
2
3
4
5
**Input:** s = "bbaaaaabb"
**Output:** 2
**Explanation:** The only solution is to delete the first two characters.
Constraints:
1
2
1 <= s.length <= 105
s[i] is 'a' or 'b'.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class Solution:
def minimumDeletions(self, s: str) -> int:
la = [0] * len(s)
lb = [0] * len(s)
i = 0
temp = 0
for k in s:
la[i] = temp
if k == 'b':
temp += 1
i += 1
j = len(s) - 1
temp = 0
for k in range(len(s)):
lb[j] = temp
if s[len(s) -k-1] == 'a':
temp += 1
j -= 1
result = 100000
for k in range(len(s)):
result = min(result, la[k] + lb[k])
return result
# for every a at i , find number of bs to left
# for every b at i , find number of as to right.
# navigate each array one by one,
# we can remove any element and then all numbers to left or right reduce by 1,
# we can remove the number altogather
#0,0,b,1,b,b,3,0
#a,a,2,a,1,1,a,0
This post is licensed under CC BY 4.0 by the author.