FastPrepMinimum Insertions to Balance a Parentheses String

Minimum Insertions to Balance a Parentheses String

IBM logoIBM● MediumFULLTIMEOA

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:

  1. String s: the initial parentheses sequence

int: the minimum number of insertions

Function

minInsertionsToBalance(s: String) → int

Examples

Example 1

s = "()))"return = 2

N/A

Example 2

s = "))(("return = 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

See IBM hiring insights
Saved
public int minInsertionsToBalance(String s) {
  // write your code here
}
s"()))"
expected2
Checking account…