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
Parentheses Balance: "(()))" → Need 1 insertion(( ) ) )Input: "(()))"Balance Rules:✓ '(' must be followed by '))'✓ '(' comes before its matching '))'✗ Single ')' cannot close '('Analysis:• First '(' matches with '))'• Second '(' has only one ')'• Need 1 more ')' for balanceSolution: "(()))" → "(()))" (insert 1 ')')Minimum insertions needed: 1
Understanding the Visualization
1
Input String
String with '(' and ')' characters
2
Balance Rule
Each '(' requires exactly 2 ')' characters
3
Minimum Insertions
Count needed characters to achieve balance
Key Takeaway
🎯 Key Insight: Each '(' needs exactly 2 ')' characters - track the balance deficit greedily
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