Magicsheet logo

Minimum Insertions to Balance a Parentheses String

Medium
36.3%
Updated 6/1/2025

Minimum Insertions to Balance a Parentheses String

1. What is this problem about?

This problem is a variation of the classic "Valid Parentheses" challenge but with a unique twist: one opening parenthesis ( must be matched by exactly two consecutive closing parentheses )).

Given a string containing only ( and ), you need to find the minimum number of insertions (either ( or )) required to make the string "balanced" according to this rule. A string is balanced if every ( has a matching )) and they are correctly nested.

2. Why is this asked in interviews?

Meta and Amazon use this problem to evaluate a candidate's ability to handle Stack-based logic and State tracking. It’s more complex than the standard balancing problem because of the "double-close" requirement, which introduces more edge cases.

Interviewer's look for:

  • Case Analysis: Can the candidate identify all scenarios (e.g., a single ) at the end, or a ) followed by a ()?
  • Greedy Logic: Can the candidate solve this in a single pass?
  • Variable Management: Tracking "needed" closing brackets versus "already open" brackets.

3. Algorithmic pattern used

The problem is best solved using a Greedy approach with a counter (simulating a stack).

  • Maintain two variables: insertions (total characters added) and needed_right (the number of ) we are currently looking for).
  • When you see a (:
    • If we needed an odd number of ), it means we had a single ) that wasn't followed by another. We must insert one ) to complete it and decrement needed_right.
    • Then, we add 2 to needed_right (because this new ( needs a pair).
  • When you see a ):
    • If it's the first of a pair, we decrement needed_right.
    • If needed_right becomes negative, it means we have an extra ). We must insert a ( and set needed_right to 1 (because the new ( needs 2, and we just used 1).

4. Example explanation

String: (()))

  1. (: needed_right becomes 2.
  2. (: needed_right becomes 4.
  3. ): needed_right becomes 3.
  4. ): needed_right becomes 2.
  5. ): needed_right becomes 1. Wait, let's look at it differently. At the end, if needed_right is 1, it means we have a trailing single ). Actually, the simplest logic:
  • ( adds 2 to "required closing".
  • ) uses 1 from "required closing".

Similar Questions