Practice/Meta/Leetcode 921. Minimum Add to Make Parentheses Valid
CodingMust
You are given a string containing only the characters '(' and ')'. Your task is to determine the minimum number of parentheses that must be inserted into the string to make it valid.
A valid parentheses string is one where:
'(' has a corresponding closing parenthesis ')'')' has a corresponding opening parenthesis '(' before itReturn the minimum number of parentheses insertions needed to make the string valid.
0 <= s.length <= 1000s consists of '(' and ')' onlyExample 1:
Input: s = "())" Output: 1 Explanation: We need to add one opening parenthesis at the beginning to match the extra closing parenthesis. Result: "(())"
Example 2:
Input: s = "(((" Output: 3 Explanation: We need to add three closing parentheses at the end to match all opening parentheses. Result: "((()))"
Example 3:
Input: s = "()" Output: 0 Explanation: The string is already valid, no additions needed.
Example 4:
Input: s = "()))((" Output: 4 Explanation: We need one opening parenthesis for the unmatched closing at position 2, and two closing parentheses for the unmatched opening ones at the end. We also need one opening for the closing at position 3. Total: 4 additions needed.