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 AB where 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
Parentheses Matching VisualizationExample: "())"(Step 1)Step 2)Step 3Counter States:Step 1: unmatched_open = 1Step 2: unmatched_open = 0Step 3: unmatched_close = 1Stack Visualization:(StackMatch!)UnmatchedResult: unmatched_open (0) + unmatched_close (1) = 1
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.
Asked in
Facebook 45 Google 38 Amazon 32 Microsoft 28
68.2K Views
Medium Frequency
~12 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen