Minimum Insertions to Balance a Parentheses String
Problem statement
Given a string that consists of left and right parentheses, '(' and ')',
balance the parentheses by inserting parentheses as necessary. Determine the minimum number of
characters that must be inserted.
Complete the function minInsertionsToBalance in the editor.
minInsertionsToBalance has the following parameter:
String s: the initial parentheses sequence
int: the minimum number of insertions
Function
minInsertionsToBalance(s: String) → intExamples
Example 1
s = "()))"return = 2N/A
Example 2
s = "))(("return = 4The first two closing parentheses have no matching opening parentheses, so two '(' characters must be inserted before them. The final two opening parentheses remain unmatched, so two ')' characters must be inserted after them. Four insertions produce "(())(())", and fewer insertions cannot resolve all four unmatched parentheses.
Constraints
- 1 ≤ length of
s≤ 105