Minimum Insertions to Balance a Parentheses String LeetCode solution in Python

1
class Solution:
2
def minInsertions(self, s: str) -> int:
3
leftbrackets = insertions = 0
4
i, n = 0, len(s)
5

6
while i < n:
7
if s[i] == "(":
8
leftbrackets += 1
9
elif s[i] == ")":
10
if i == n - 1 or s[i + 1] != ")":
11
insertions += 1
12
else:
13
i += 1
14

15
if not leftbrackets:
16
insertions += 1
17
else:
18
leftbrackets -= 1
19

20
i += 1
21

22
return leftbrackets * 2 + insertions

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0