Given a parentheses string s containing only the characters '(' and ')'. A parentheses string is balanced if: - Any left parenthesis '(' must have a corresponding two consecutive right parenthesis '))'. - Left parenthesis '(' must go before the corresponding two consecutive right parenthesis '))'. In other words, we treat '(' as an opening parenthesis and '))' as a closing parenthesis. For example, "())", "())(())))" and "(())())))" are balanced, ")()", "()))" and "(()))" are not balanced. You can insert the characters '(' and ')' at any position of the string to balance it if needed. Return the minimum number of insertions needed to make s balanced.
Example 1
Input: s = (()))
Output: 1
Explanation: The second '(' is closed by '))', but the first '(' is left with only one ')'. Adding one more ')' at the end gives '(())))', which is balanced.
Example 2
Input: s = ())
Output: 0
Explanation: The single '(' is already closed by the two ')' after it, so the string is balanced and needs no insertions.
Example 3
Input: s = ))())(
Output: 3
Explanation: Add one '(' so the first '))' has an opener, and add '))' to close the trailing '(' — three insertions in total.
Scan left to right, track how many '(' are still waiting for their '))', and count an insertion the moment the rule is violated.
Run checks all cases above. Submit evaluates all test cases.