19. Min Add to Make Parentheses Valid
โ GFG solution to the Min Add to Make Parentheses Valid problem: find minimum parentheses to add using greedy single-pass algorithm. ๐
The problem can be found at the following link: ๐ Question Link
๐งฉ Problem Description
You are given a string s consisting only of the characters '(' and ')'. Your task is to determine the minimum number of parentheses (either '(' or ')') that must be inserted at any positions to make the string s a valid parentheses string.
A parentheses string is considered valid if:
Every opening parenthesis
'('has a corresponding closing parenthesis')'.Every closing parenthesis
')'has a corresponding opening parenthesis'('.Parentheses are properly nested.
๐ Examples
Example 1
Input: s = "(()("
Output: 2
Explanation: There are two unmatched '(' at the end, so we need to add two ')' to make the string valid.Example 2
Input: s = ")))"
Output: 3
Explanation: Three '(' need to be added at the start to make the string valid.Example 3
๐ Constraints
$1 \le \text{s.size()} \le 10^5$
$\text{s}[i] \in {'\text{(}', '\text{)}'}$
โ
My Approach
The optimal approach uses a Greedy Single-Pass Algorithm to count unmatched opening and closing parentheses:
Greedy Counting Strategy
Initialize Counters:
open: Track unmatched opening brackets'('close: Track unmatched closing brackets')'that cannot be paired
Single Pass Through String:
For each
'(': Incrementopencounter (potential match available)For each
')':If
open > 0: Decrementopen(successful pairing)Else: Increment
close(unmatched closing bracket)
Calculate Result:
Total insertions needed =
open + closeopenrepresents unmatched opening brackets (need closing brackets)closerepresents unmatched closing brackets (need opening brackets)
Why This Works:
Greedy approach: Always try to match closing brackets with available opening brackets
Left-to-right traversal ensures optimal pairing
No backtracking needed as each decision is locally optimal
๐ Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), where n is the length of the string. We make a single pass through the string, examining each character exactly once.
Expected Auxiliary Space Complexity: O(1), as we only use a constant amount of additional space for the two integer counters regardless of input size.
๐งโ๐ป Code (C++)
โ Code (Java)
๐ Code (Python)
๐ง Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: ๐ฌ Any Questions?. Let's make this learning journey more collaborative!
โญ If you find this helpful, please give this repository a star! โญ
๐Visitor Count
Last updated