Skip to content

Commit 2fe87be

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

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
int minInsertions(string s) {
7+
int add = 0, bal = 0;
8+
for (const auto& c: s) {
9+
if (c == '(') {
10+
if (bal % 2 > 0) {
11+
++add; // add ')' to make sure consecutive ')'
12+
--bal;
13+
}
14+
bal += 2;
15+
} else {
16+
--bal;
17+
if (bal < 0) {
18+
++add; // add '('
19+
bal += 2;
20+
}
21+
}
22+
}
23+
return add + bal;
24+
}
25+
};

0 commit comments

Comments
 (0)