249. Minimum Add to Make Parentheses Valid

MediumStringString

Given a string s of '(' and ')', return the minimum number of parentheses to add (anywhere) to make the string valid (every open has a matching close and vice versa).

Input: A quoted parentheses string.

Output: Integer — minimum additions.

Examples

Example 1
Input: "())"
Output: 1
Explanation: Add one '(' -> '(())'.
Example 2
Input: "((("
Output: 3
Explanation: Add three ')'.
Example 3
Input: "()"
Output: 0
Explanation: Already valid.

Constraints

Asked by

MetaAmazonIBMBloombergGoogleMicrosoft
Solve this problem in the editor →