AlgoMaster Logo

Minimum Add to Make Parentheses Valid

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Stack Based Solution

Intuition:

The problem is to ensure that each open parenthesis '(' has a corresponding closing parenthesis ')'. A simple approach involves using a stack data structure to keep track of unmatched parentheses. We iterate through the string, pushing open parentheses onto the stack and popping when we encounter a closing parenthesis that matches. If a closing parenthesis has no matching open parenthesis (the stack is empty), it indicates an unmatched closing parenthesis. By the end of the string traversal, the size of the stack plus any unmatched closing parentheses encountered gives the minimum additions needed to make the string valid.

Code:

2. Counting Unmatched Parentheses

Intuition:

Instead of using a stack, we can optimize the space by simply counting the number of unmatched open and close parentheses. We maintain two counters: one for unmatched open parentheses (open) and another for unmatched closing parentheses (close). As we iterate through the string, for every ( encountered, we increment the open counter. For every ), if there is a corresponding unmatched open parenthesis, we decrement the open counter (effectively "matching" them). Otherwise, we increment the close counter indicating an unmatched ).

Code: