635. Minimum Add to Make Parentheses Valid

MediumStackStackGreedyString

Given a string s of '(' and ')', return the minimum number of parentheses (of either type) that must be inserted anywhere so the result is a valid balanced string. The input is JSON {s}.

Input: JSON {s}.

Output: Integer — the minimum insertions needed.

Examples

Example 1
Input: {"s":"())"}
Output: 1
Explanation: Add one '(' at the front.
Example 2
Input: {"s":"((("}
Output: 3
Explanation: Need three closings.
Example 3
Input: {"s":"()()"}
Output: 0
Explanation: Already valid.

Constraints

Asked by

MetaAmazonIBMBloombergGoogleMicrosoft
Solve this problem in the editor →