Problem · String

Minimum Insertions to Balance a Parentheses String

Learn this problem
MediumIBMFULLTIMEOA
See IBM hiring insights

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.

Function

minInsertionsToBalance(s: String) → int

Complete the function minInsertionsToBalance in the editor.

minInsertionsToBalance has the following parameter:

  1. String s: the initial parentheses sequence

Returns

int: the minimum number of insertions

Examples

Example 1

s = "()))"return = 2
N/A

Example 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

drafts saved locally
public int minInsertionsToBalance(String s) {
  // write your code here
}
s"()))"
expected2
checking account