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
More IBM problems
- Parent Process NumberOA · Seen Jul 2026
- Request Retry CountOA · Seen Jul 2026
- Count Strictly Increasing Subsequences of Length 3OA · Seen Jul 2026
- Maximum Requests in a Time WindowOA · Seen Jul 2026
- Query Type Frequency WindowOA · Seen Jul 2026
- Minimum Number of Non-Empty Disjoint SegmentsOA · Seen Jul 2026
- Spam Text ClassificationOA · Seen Jul 2026
- Count Ideal NumbersOA · Seen Jun 2026