Minimum Insertions to Balance Parentheses
Problem statement
Given a string s containing only '(' and ')', return the minimum number of parentheses that must be inserted at any positions to make the string valid.
A valid parenthesis string has every opening parenthesis matched with a later closing parenthesis, and every closing parenthesis matched with an earlier opening parenthesis.
Function
minInsertionsToBalance(s: String) → intExamples
Example 1
s = "())"return = 1Insert one opening parenthesis before the final closing parenthesis.
Example 2
s = "((("return = 3Each unmatched opening parenthesis needs a closing parenthesis.
Example 3
s = "()"return = 0The string is already valid.
Constraints
0 <= s.length <= 100000.scontains only'('and')'.