[LeetCode] Minimum Insertions to Balance a Parentheses String

1541. Minimum Insertions to Balance a Parentheses String

Given a parentheses string s containing only the characters ‘(‘ and ‘)’. A parentheses string is balanced if:

  • Any left parenthesis ‘(‘ must have a corresponding two consecutive right parenthesis ‘))’.
  • Left parenthesis ‘(‘ must go before the corresponding two consecutive right parenthesis ‘))’.

In other words, we treat ‘(‘ as an opening parenthesis and ‘))’ as a closing parenthesis.

  • For example, “())”, “())(())))” and “(())())))” are balanced, “)()”, “()))” and “(()))” are not balanced.

You can insert the characters ‘(‘ and ‘)’ at any position of the string to balance it if needed.

Return the minimum number of insertions needed to make s balanced.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
int minInsertions(string s) {
int po = 0, o = 0, c = 0, n = s.length(), i = 0;
for(int i = 0; i < n; i++) {
if(s[i] == '(') po++;
else {
if(i + 1 < n and s[i + 1] == ')') {
if(po) po--;
else o++;

i += 1;
} else {
if(po) po--, c++;
else c++, o++;
}
}
}

return po * 2 + o + c;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/30/PS/LeetCode/minimum-insertions-to-balance-a-parentheses-string/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.