Minimum Add to Make Parentheses Valid

Updated on 10 June, 2025
Minimum Add to Make Parentheses Valid header image

Problem Statement

A well-formed or valid parentheses string adheres to specific rules that define its structure. Such a string is considered valid if:

  • It is an empty string,
  • It can be represented as AB, where both A and B are valid parentheses strings,
  • It can be denoted as (A), where A is a valid parentheses string.

Given a string s consisting solely of '(' and ')', you may insert a parenthesis at any position in order to make the string valid. The goal is to determine the minimum number of insertions required to transform s into a valid parentheses string. This problem is not just a matter of counting mismatches but strategically inserting parentheses to balance the string efficiently.

For example, with s = "()))", inserting an additional '(' at an appropriate position could help in balancing the parentheses, resulting in a valid string like "(()))".

Examples

Example 1

Input:

s = "())"

Output:

1

Example 2

Input:

s = "((("

Output:

3

Constraints

  • 1 <= s.length <= 1000
  • s[i] is either '(' or ')'.

Approach and Intuition

The task requires transforming an irregular parentheses string into a valid one with the minimal number of operations, making it a challenge of efficient string manipulation and balance maintenance. Here's how you might consider approaching problem-solving:

  1. Initialize Counters: Start by initializing two counters, say leftNeeded and rightNeeded, to track the number of '(' and ')' needed to balance the string at any point as you iterate through it.

  2. Iterate through the String:

    • For each character:
      • If it is '(', it potentially increases the need for a ')' in the future to balance it.
      • If it is ')', check if there is an unmatched '(' (if leftNeeded > 0). If so, decrease leftNeeded as this ')' can balance a previous '('. If not, increment rightNeeded since you'll need an extra '(' to balance this ')'.
  3. Calculate Total Insertions: By the end of the string iteration, leftNeeded will tell you how many ')' are still needed, and rightNeeded will tell you how many '(' are insufficient. The sum of these two values will provide the total number of insertions required.

  4. Optimal Insertions: The optimal number of insertions is essentially ensuring that at no point in the string there is a ')' that does not have a preceding matched '(' (which would require inserting new '(' at the beginning or in the middle) and that the string ends with all '(' having matching ')'.

This problem is fundamentally about maintaining balance between opening and closing brackets as you move through the string, and strategically planning insertions to correct imbalances as efficiently as possible.

Solutions

  • C++
  • Java
  • Python
cpp
class Solution {
public:
    int minimumInsertionsToBalance(string str) {
        int open = 0;
        int requiredInserts = 0;
        for (char ch : str) {
            if (ch == '(') {
                open++;
            } else {
                // Close one if an opening bracket was seen
                open > 0 ? open-- : requiredInserts++;
            }
        }
        // Add the extra required closing brackets to balance remaining open ones
        return requiredInserts + open;
    }
};

This C++ solution focuses on determining the minimum number of insertions required to make a string of parentheses valid. The approach utilizes a counter mechanism to track unbalanced parentheses as the string is processed character by character.

  • Initialize two counters:

    • open to keep track of unmatched opening brackets.
    • requiredInserts to count the insertions needed for balancing closing brackets.
  • Iterate through each character in the string:

    • Increment the open counter for every '(' encountered.
    • For each ')', check if there's an unmatched '(' available:
      • If yes, decrement the open counter.
      • If no opening bracket is available, increment the requiredInserts counter by one.
  • After completing the iteration through the string, add any remaining unmatched opening brackets to the requiredInserts. This sum represents the total insertions needed to balance the parentheses.

The function finally returns the total number of insertions (requiredInserts + open) required to make the entire string of parentheses valid. This method effectively accounts for both excess opening and closing brackets, ensuring the string achieves proper balance with minimal modifications.

java
class Solution {

    public int addMinParentheses(String s) {
        int openCount = 0;
        int closeNeeded = 0;

        for (char ch : s.toCharArray()) {
            if (ch == '(') {
                openCount++;
            } else {
                if (openCount > 0) {
                    openCount--;
                } else {
                    closeNeeded++;
                }
            }
        }

        return closeNeeded + openCount;
    }
}

This Java solution addresses the problem of determining the minimum number of additional parentheses required to make an input string of parentheses balanced. The solution utilizes two counters: openCount for tracking unbalanced opening parentheses '(' and closeNeeded for tracking the necessary closing parentheses ')' to balance the string.

  • The method addMinParentheses(String s) iterates through each character in the string.
  • If the character is '(', increment openCount.
  • If the character is ')':
    • If openCount is greater than zero, decrement openCount (successfully balancing one opening with a closing bracket).
    • If openCount is zero, increment closeNeeded (a closing bracket without a matching opening bracket).

The method returns the sum of closeNeeded and openCount. The total represents the minimum insertions needed where openCount shows the number of unmatched '(' and closeNeeded shows the unmatched ')'. This approach ensures that all opening and closing brackets can form pairs by the end of the string analysis.

python
class Solution:
    def minimumInsertionsToBalance(self, parentheses: str) -> int:
        open_count = 0
        additions_needed = 0

        for char in parentheses:
            if char == "(":
                open_count += 1
            elif open_count > 0:
                open_count -= 1
            else:
                additions_needed += 1

        return additions_needed + open_count

The Python solution provided tackles the problem of making an unbalanced string of parentheses valid through the minimum number of insertions. The function minimumInsertionsToBalance accepts a string of parentheses and determines how many additions are necessary to balance it.

The solution works as follows:

  1. Initialize two counters: open_count to track the number of unmatched opening parentheses and additions_needed for the count of insertions required.

  2. Iterate through each character in the input string.

    • If the character is an opening parenthesis "(", increment open_count.
    • If it's a closing parenthesis ")", check if there’s an unmatched opening parenthesis. If so, decrement open_count. Otherwise, increase additions_needed since an unmatched closing parenthesis needs a corresponding opening one.
  3. After processing all characters, add any remaining unmatched opening parentheses (open_count) to additions_needed. This accounts for each unmatched opening parenthesis needing a matching closing parenthesis.

The result, additions_needed + open_count, is the total number of insertions needed to balance the parentheses fully. This approach efficiently ensures each parenthesis is properly paired by directly counting mismatches and addressing them, achieving the balance with the minimum additions.

Comments

No comments yet.