Minimum Insertions to Balance a Parentheses String

Given a parentheses string s containing only the characters '(' and ')'. A parentheses string is balanced if:

  • Any left parenthesis '(' must have a corresponding two consecutive right parentheses '))'.
  • A left parenthesis '(' must come before its corresponding two consecutive right parentheses '))'.

In other words, treat '(' as an opening parenthesis and '))' as a closing parenthesis.

You can insert the characters '(' and ')' at any position of the string to balance it if needed.

Return the minimum number of insertions needed to make s balanced.

Example 1
Inputs = "(()))"
Output1
The second '(' has two matching '))', but the first '(' has only ')' matching, so one more ')' must be added at the end.
Example 2
Inputs = "())"
Output0
The string is already balanced.

Constraints

  • 1 <= s.length <= 10^5
  • s consists of '(' and ')' only.

Asked at 4 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate