Minimum Add to Make Parentheses Valid

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.

Return the minimum number of moves required to make s valid.

Example 1
Inputs = "())"
Output1
Adding one opening parenthesis makes the string valid.
Example 2
Inputs = "((("
Output3
Adding three closing parentheses makes the string valid.

Constraints

  • 1 <= s.length <= 1000
  • s[i] is either '(' or ')'.

Asked at 8 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate