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 INPUT Parentheses String s: ( idx 0 ) idx 1 ) idx 2 Input: s = "())" Goal: Make string valid by adding minimum parentheses Valid examples: "()" "(())" "()()" Invalid: "())" "(((" ")(" ALGORITHM STEPS 1 Initialize Counters open = 0, close = 0 2 Process '(' at idx 0 open++ --> open = 1 3 Process ')' at idx 1 open > 0? Yes! open-- open = 0 (matched!) 4 Process ')' at idx 2 open > 0? No! close++ --> close = 1 Balance Tracking Char open close ( 1 0 ) 0 0 ) 0 1 FINAL RESULT Result = open + close Result = 0 + 1 = 1 OK Solution Visualization: Original: ( ) ) Fixed: ( ( ) ) Add 1 '(' at start Output: 1 Key Insight: Track unmatched '(' with 'open' counter. For each ')', either match it with an open '(' (decrement open) or count it as needing a '(' (increment close). Final answer = open + close = unmatched parentheses. TutorialsPoint - Minimum Add to Make Parentheses Valid | Greedy Balance Tracking
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