Medium
032Minimum Add to Make Parentheses Valid
Return the minimum number of parentheses that must be added to make s valid.
EXAMPLES
Example 1
Input
{
"s": "())"
}
Output
1FUNCTION SHAPE
s: string→intSOLUTION NOTE
Count unmatched '(' and unmatched ')' separately. Answer is their sum.
Reveal reference solution +
pythonREFERENCE
def minAddToMakeValid(self, s: str) -> int:
open_count = 0
close_needed = 0
for c in s:
if c == '(':
open_count += 1
elif open_count > 0:
open_count -= 1
else:
close_needed += 1
return open_count + close_neededTime
O(n)Space
O(1)