1021. Remove Outermost Parentheses

1. Description

A balanced parentheses string matches every ‘(’ with a later ‘)’, leaving no unmatched characters. The empty string is also balanced.
A primitive string is a nonempty balanced string that cannot be split into two nonempty balanced strings.
Given a balanced string s, split it into primitive components, delete the first and last parentheses of each component, and concatenate what remains. Return the resulting string.

2. Example

Example 1

Input: s = “(()())(())”
Output: “()()()”
Explanation: The components “(()())” and “(())” become “()()” and “()”.

Example 2

Input: s = “(()())(())(()(()))”
Output: “()()()()(())”
Explanation: Removing the outer pair from each component leaves “()()”, “()”, and “()(())”.

Example 3

Input: s = “()()”
Output: ""
Explanation: Both components are “()”, so neither contributes any characters.

3. Constraints

  • 1 <= s.length <= $10^5$
  • Each character of s is either ‘(’ or ‘)’.
  • s is guaranteed to be balanced.

4. Solutions

Counting Depth

n = str.size()
Time complexity: O(n)
Space complexity: O(1), excluding the output string

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
    string removeOuterParentheses(const string &str) {
        string result;
        int balance = 0;

        for (char c : str) {
            if (c == '(') {
                if (balance > 0) {
                    result.push_back(c);
                }
                ++balance;
            } else {
                --balance;
                if (balance > 0) {
                    result.push_back(c);
                }
            }
        }

        return result;
    }
};
comments powered by Disqus