Minimum Insertions to Balance a Parentheses String
Learn this problemProblem 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.
Function
minInsertionsToBalance(s: String) → int
Complete the function minInsertionsToBalance in the editor.
minInsertionsToBalance has the following parameter:
String s: the initial parentheses sequence
Returns
int: the minimum number of insertions
Examples
Example 1
s = "()))"return = 2Example 2
s = "))(("return = 4🫐 Source note: Corrected on 2026-07-17. This example now uses "))((", matching the source's second walkthrough and its output of 4.
The 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