Minimum Insertions to Balance a Parentheses String - Problem

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 parenthesis '))'.
  • Left parenthesis '(' must go before the corresponding two consecutive right parenthesis '))'.

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

For example, "())", "())(()))" and "(())()))" are balanced, ")()", "()))" and "(()))" are not balanced.

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.

Input & Output

Example 1 — Basic Unbalanced
$ Input: s = "(()))"
Output: 1
💡 Note: We have "(()))" which has one '(' needing two ')', but there are three ')'. The second and third ')' form a valid pair ')', but the last ')' is unmatched. We need to insert one ')' to make it "(()))".
Example 2 — Multiple Opens
$ Input: s = "((("
Output: 6
💡 Note: We have 3 opening parentheses, each needing 2 closing parentheses. So we need 3 × 2 = 6 insertions: "(((" → "((())))".
Example 3 — Mixed Case
$ Input: s = "())("
Output: 2
💡 Note: "())" is balanced (one '(' with ')'), but we have an extra ')' and an unmatched '(' at the end. Need to insert one '(' for the extra ')' and two ')' for the final '('.

Constraints

  • 1 ≤ s.length ≤ 105
  • s consists of only '(' and ')'

Visualization

Tap to expand
Minimum Insertions to Balance Parentheses INPUT String s = "(()))" ( idx 0 ( idx 1 ) idx 2 ) idx 3 ) idx 4 Balance Rule: '(' requires '))' One '(' matches TWO ')' Input Values s = "(()))" Length: 5 ALGORITHM STEPS 1 Initialize Counters open=0, insertions=0 2 Scan Characters '(' increments open 3 Handle ')' Pairs Check for '))' or insert 4 Match or Insert '(' If no open, add insertion Trace: "(()))" idx char open insert note 0 ( 1 0 +open 1 ( 2 0 +open 2 ) 2 1 +1 ins 3 ) 1 1 -open 4 ) 1 1 wait Final: open=1 needs 2 more ')' FINAL RESULT Balanced String After Insertion: ( ( ) ) ) ) INSERTED "(())" becomes "(()))" with 1 insertion Bracket Matching: ( matches )) OK ( matches )) OK All brackets balanced! Output 1 Minimum Insertions Key Insight: Each '(' needs TWO ')' to close. Track open brackets and pending ')'. When ')' is alone, insert another ')' to form a pair. If no '(' available when we see '))', insert '(' first. Final answer = insertions during scan + (remaining open brackets * 2). TutorialsPoint - Minimum Insertions to Balance a Parentheses String | Greedy Balance Tracking
Asked in
Facebook 45 Google 38 Microsoft 32 Amazon 28
87.5K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen