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)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
    int minAddToMakeValid(const string &str) {
        int balance = 0, additions = 0;
        for (char c : str) {
            if (c == '(') {
                ++balance;
            } else {
                --balance;
                if (balance < 0) {
                    ++additions;
                    balance = 0;
                }
            }
        }

        additions += balance;

        return additions;
    }
};
comments powered by Disqus