Minimum Insertions to Balance a Bracket String

Implement minInsertionsToBalance

Given a string s consisting only of '(' and ')', find the minimum number of parentheses that need to be inserted anywhere in the string to make it balancedBalancedEvery '(' has a matching ')' later in the string, and every ')' has a matching '(' earlier — the same property "valid parentheses" checks, just quantified as a repair cost instead of a yes/no.. Unlike checking whether a bracket string is already valid, this asks how far from valid it is. A single running counter does the job in one pass: track how many '(' are currently unmatched. Every ')' either closes one of them (decrement) or, if none are open, is itself unmatched and needs a '(' inserted before it (tally it). Whatever's still open at the very end needs a ')' inserted after it. The total repair cost is exactly the sum of those two kinds of damage — no backtracking or re-scanning required.

Example 1:

Input: s = "(()"

Output: 1

Example 2:

Input: s = "))(("

Output: 4

Example 3:

Input: s = "()()"

Output: 0

+ 6 hidden test cases run on Submit.

Constraints:

  • 1 ≤ s.length ≤ 10⁴
  • s consists only of the characters '(' and ')'

s =

(()