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
Minimum Add to Make Parentheses Valid()))Invalid StringTrack BalanceOpening: 0 unmatchedClosing: 1 unmatchedResult: 0 + 1 = 1
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
Asked in
Facebook 25 Google 20 Amazon 15
125.0K Views
Medium Frequency
~15 min Avg. Time
2.2K 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