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
Input: s = ")()()"
Output: 1
Explanation: The very first ')' is unmatched, so we need to add one '(' at the beginning.
๐ 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
'('
: Incrementopen
counter (potential match available)For each
')'
:If
open > 0
: Decrementopen
(successful pairing)Else: Increment
close
(unmatched closing bracket)
Calculate Result:
Total insertions needed =
open + close
open
represents unmatched opening brackets (need closing brackets)close
represents 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++)
class Solution {
public:
int minParentheses(string& s) {
int open = 0, close = 0;
for (char c : s) {
if (c == '(') open++;
else if (c == ')') open > 0 ? open-- : close++;
}
return open + close;
}
};
โ Code (Java)
class Solution {
public int minParentheses(String s) {
int open = 0, close = 0;
for (char c : s.toCharArray()) {
if (c == '(') open++;
else if (c == ')') if (open > 0) open--; else close++;
}
return open + close;
}
}
๐ Code (Python)
class Solution:
def minParentheses(self, s):
open = close = 0
for c in s:
if c == '(':
open += 1
elif c == ')':
if open > 0:
open -= 1
else:
close += 1
return open + close
๐ง 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