Minimum Add to Make Parentheses Valid
Given a string s of '(' and ')' parentheses, return the minimum number of parentheses you must add to make the resulting string valid. A valid parentheses string has every '(' matched with a corresponding ')' in the correct order.
Track the balance as you iterate. When you see '(', increment balance. When you see ')', if balance > 0, decrement it (matching a previous '('), otherwise increment the add count (we need to add a matching '('). After the loop, the remaining balance is the number of ')' needed to close unmatched '('.
Time complexity is O(n) and space is O(1). This greedy approach works because parentheses can only be matched in order, so we never need to reconsider decisions.
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
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.
