Skip to content

Commit 2ac8172

Browse files
authored
Create minimum-insertions-to-balance-a-parentheses-string.py
1 parent 2fe87be commit 2ac8172

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# Time: O(n)
2+
# Space: O(1)
3+
4+
class Solution(object):
5+
def minInsertions(self, s):
6+
"""
7+
:type s: str
8+
:rtype: int
9+
"""
10+
add, bal = 0, 0
11+
for c in s:
12+
if c == '(':
13+
if bal > 0 and bal%2:
14+
add += 1
15+
bal -= 1
16+
bal += 2
17+
else:
18+
bal -= 1
19+
if bal < 0:
20+
add += 1
21+
bal += 2
22+
return add + bal

0 commit comments

Comments
 (0)