Minimum Add to Make Parentheses Valid
Calculate the minimum number of parentheses to insert to make a string valid using balance counters in O(1) auxiliary space.
01The problem
A parentheses string is valid if and only if:
- It is the empty string,
- It can be written as
AB(Aconcatenated withB), whereAandBare valid strings, or - It can be written as
(A), whereAis 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.
| Input | Output | Why |
|---|---|---|
"())" | 1 | One '(' inserted at the beginning makes it "()()" |
"(((" | 3 | Three ')' inserted at the end make it "((()))" |
"()" | 0 | Already valid; 0 insertions needed |
Constraints: 1 <= s.length <= 1000, s[i] is either '(' or ')'.
Loading the rest of the lesson…