1541. Minimum Insertions to Balance a Parentheses String

1. Description

Given a string s made of ‘(’ and ‘)’, balance it using a special matching rule: each ‘(’ needs a matching pair of consecutive ‘)’ characters appearing after it. Thus, ‘))’ acts as a single closing unit.
You may insert either character anywhere in s, including at the beginning or end. Return the fewest insertions required to balance the string.

2. Example

Example 1

Input: s = “(()))”
Output: 1
Explanation: Appending ‘)’ produces “(())))”, which satisfies the matching rule.

Example 2

Input: s = “())”
Output: 0
Explanation: No insertions are needed.

Example 3

Input: s = “))())(”
Output: 3
Explanation: Insert ‘(’ at the beginning and append ‘))’ at the end.

3. Constraints

  • 1 <= s.length <= $10^5$
  • 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
22
23
24
25
class Solution {
public:
    int minInsertions(const string &str) {
        int balance = 0, count = 0;
        for (char c : str) {
            if (c == '(') {
                if (balance % 2 == 1) {
                    ++count;
                    --balance;
                }

                balance += 2;
            } else {
                balance -= 1;

                if (balance < 0) {
                    ++count;
                    balance += 2;
                }
            }
        }

        return count + balance;
    }
};
comments powered by Disqus