Minimum Add to Make Parentheses Valid - Problem
A parentheses string is valid if and only if:
- It is the empty string
- It can be written as
AB(A concatenated with B), where A and B are valid strings - It can be written as
(A), where A is a valid string
You are given a parentheses string s. In one move, you can insert a parenthesis at any position of the string.
For example, if s = "())", you can insert an opening parenthesis to be "(())" or a closing parenthesis to be "())".
Return the minimum number of moves required to make s valid.
Input & Output
Example 1 — Unmatched Closing
$
Input:
s = "())"
›
Output:
1
💡 Note:
We have one '(' and two ')'. The first ')' matches with '(', but the second ')' is unmatched. We need to add one '(' at the beginning to make it valid: "(())".
Example 2 — Unmatched Opening
$
Input:
s = "((("
›
Output:
3
💡 Note:
We have three unmatched '(' characters. We need to add three ')' characters to make it valid: "((()))".
Example 3 — Empty String
$
Input:
s = ""
›
Output:
0
💡 Note:
Empty string is already valid, no additions needed.
Constraints
- 1 ≤ s.length ≤ 1000
- s[i] is either '(' or ')'
Visualization
Tap to expand
Understanding the Visualization
1
Input
Invalid parentheses string with mismatched pairs
2
Process
Count unmatched opening and closing parentheses
3
Output
Minimum additions needed to make string valid
Key Takeaway
🎯 Key Insight: Count unmatched parentheses by tracking balance - negative balance means unmatched closing, positive balance means unmatched opening
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code