Minimum Add to Make Parentheses Valid
Given a string containing only parentheses '(' and ')', determine the minimum number of parentheses you must add to make the string valid. A valid parentheses string has every opening parenthesis matched with a closing one in the correct order.
For example, "())" needs 1 addition: add '(' at the front to get "(())". "(((" needs 3 additions: add ")))" at the end. "()" needs 0 additions. An empty string needs 0.
This problem teaches stack-based or counter-based parentheses balancing. It is a simpler version of the classic valid-parentheses problem, focusing on counting unmatched parentheses rather than validating intermediate states.
The solution uses a counter: iterate through each character. If it is '(', increment the counter. If it is ')' and the counter is positive, decrement it (matching a previous '('). If it is ')' and the counter is zero, increment a needed counter (this ')' is unmatched). The total additions needed is the sum of the final counter (unmatched '(') and the needed counter (unmatched ')').
Edge cases include an empty string (return 0), only opening parentheses (return the count), only closing parentheses (return the count), and already-valid strings (return 0).
Example Input & Output
2 to close, 2 to open
Add one '(' at start
Empty is valid
Already valid
Add three ')' at end
Algorithm Flow
Solution Approach
Use a counter to track unmatched opening parentheses and count unmatched closing ones.
Track open parentheses with a counter. For '(' increment open. For ')', if there is an open parenthesis to match, decrement open. Otherwise, this ')' is unmatched — increment add. The total additions needed is open + add: open unmatched '(' plus add unmatched ')'.
Time complexity is O(n), space complexity is O(1).
Best Answers
class Solution {
public int solution(String s) {
int add=0,bal=0;
for(int i=0;i<s.length();i++){char c=s.charAt(i);
if(c=='(')bal++;
else if(bal>0)bal--;
else add++;
}return add+bal;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
