Minimum Add to Make Parentheses Valid

A parentheses string is valid if it is empty, if it is `AB` where `A` and `B` are valid, or if it is `(A)` where `A` is valid. You are given a string `s` of `(` and `)`. In one move you may insert a single parenthesis anywhere in the string. Return the minimum number of moves needed to make `s` valid.

30:00

Minimum Add to Make Parentheses Valid
medium
Free written solution
Topics
Companies

A parentheses string is valid if it is empty, if it is AB where A and B are valid, or if it is (A) where A is valid. You are given a string s of ( and ). In one move you may insert a single parenthesis anywhere in the string. Return the minimum number of moves needed to make s valid.

Example 1:
Input: {"s":"())"}
Output: 1
Constraints:
  • 1≤s.length≤10001 \leq s.\text{length} \leq 1000

  • s[i] is either '(' or ')'.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"s":"())"}

s; same colour = matched pair, dashed green = inserted

(

0

)

1

)

2

Scan left to right with two counters: open = '(' still waiting for a partner, added = '(' we had to insert.

open: '(' waiting for a partner

0

none waiting

added: '(' inserted for a lone ')'

0

pairs matched 0

Variables
VariableValue
open0
added0
DepthFunction Call
Stack empty
0/5