Minimum Add to Make Parentheses Valid - Problem
Imagine you're a code editor that needs to automatically balance parentheses in user code. You have a string containing only '(' and ')' characters, but some parentheses are missing!
A valid parentheses string follows these rules:
- It's either an empty string
- It can be written as
ABwhere both A and B are valid - It can be written as
(A)where A is valid
Your mission: Find the minimum number of parentheses you need to insert anywhere in the string to make it perfectly balanced.
For example, if you have "())", you could insert one opening parenthesis at the beginning to get "(())" - that's just 1 insertion!
Input & Output
example_1.py โ Basic Case
$
Input:
s = "())"
โบ
Output:
1
๐ก Note:
We have one unmatched closing parenthesis. We need to add one opening parenthesis at the beginning: "(())" to make it valid.
example_2.py โ Multiple Unmatched
$
Input:
s = "((("
โบ
Output:
3
๐ก Note:
We have three unmatched opening parentheses. We need to add three closing parentheses at the end: "((()))" to make it valid.
example_3.py โ Mixed Unmatched
$
Input:
s = "())()"
โบ
Output:
1
๐ก Note:
The first ')' has no matching '(' before it, so we need to add one opening parenthesis. Result: "(())()" requires 1 addition.
Constraints
- 1 โค s.length โค 1000
- s[i] is either '(' or ')'
- Note: The string contains only parentheses characters
Visualization
Tap to expand
Understanding the Visualization
1
Initialize Counters
Start with unmatched_open = 0, unmatched_close = 0
2
Process Opening '('
Increment unmatched_open counter (add plate to stack)
3
Process Closing ')'
If unmatched_open > 0, decrement it (remove plate); otherwise increment unmatched_close
4
Calculate Result
Return unmatched_open + unmatched_close (plates + missing covers)
Key Takeaway
๐ฏ Key Insight: We only need to track two types of errors: closing parentheses that appear without a matching opening one (need to add opening), and opening parentheses that never get closed (need to add closing). A single pass with two counters captures both cases optimally.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code