921. Minimum Add to Make Parentheses Valid
1. Description
Given a string s containing parentheses, find the fewest insertions needed to make it valid. Each insertion adds one ‘(’ or ‘)’ anywhere in the string, including either end.
A valid string pairs every opening parenthesis with a later closing parenthesis, without leaving any unmatched characters. The empty string is valid as well.
2. Example
Example 1
Input: s = “())”
Output: 1
Example 2
Input: s = “(((”
Output: 3
3. Constraints
- 1 <= s.length <= 1000
- Each character of s is either ‘(’ or ‘)’.
4. Solutions
Greedy
n = str.size()
Time complexity: O(n)
Space complexity: O(1)
| |