277. Minimum Insertions to Balance Parentheses

HardStringString

Given a parentheses string s, a balanced string requires every '(' to be matched by two consecutive ')'. Return the minimum number of insertions (of '(' or ')') needed to make s balanced.

Input: A quoted parentheses string.

Output: Integer — minimum insertions.

Examples

Example 1
Input: "(()))"
Output: 1
Explanation: One insertion balances it.
Example 2
Input: "())"
Output: 0
Explanation: Already balanced: one '(' with two ')'.
Example 3
Input: "(((((("
Output: 12
Explanation: Each '(' needs '))'.

Constraints

Asked by

AmazonGoogleMicrosoftMetaAdobe
Solve this problem in the editor →