Remove Outermost Parentheses (LeetCode 1021): Solution and Explanation
A valid parentheses string splits uniquely into primitives: valid pieces that cannot be split further, such as (()()) and (()). Remove the outermost pair of parentheses from each primitive and return what is left.
Intuition
You could find the primitives first: scan with a balance counter, and every time the balance returns to zero you have reached the end of one primitive. Then slice off its first and last character. That works, but it needs the start index of each piece.
There is a simpler way to say which characters are outer ones. Picture each character at its nesting depth. A primitive always starts with a ( read at depth 0, and it ends with the ) that brings the depth back to 0. Those two characters sit on the ground level. Every other character in the primitive is nested at least one level deep.
So the decision is local: a character is dropped exactly when it sits at depth 0, and kept otherwise. One counter answers that question as you scan, with no need to find the primitives explicitly.
The only care is the order of the check and the update. For (, check the depth before increasing it. For ), decrease first and then check, so the closing outer ) sees depth 0.
Approach: Depth counter
- Set
depth = 0and start an empty output. - For
(: ifdepth > 0, append it. Then incrementdepth. - For
): decrementdepth. Then, ifdepth > 0, append it. - Return the output joined into a string.
Step-by-step example
s = "(()())(())"
- Index 0 '(' arrives at depth 0, so it is the outer '(' of the first primitive. Skip it; depth becomes 1.
- Indexes 1 to 4 are "()()". Each '(' arrives at depth 1 and each ')' leaves depth 1, so all four are copied.
- Index 5 ')' drops depth to 0, closing the first primitive. It is the outer ')', so skip it.
- Index 6 '(' opens the second primitive at depth 0. Skip it; depth becomes 1.
- Index 7 '(' and index 8 ')' are nested, so copy them.
- Index 9 ')' returns depth to 0 and is skipped. The output is "()()" + "()" = "()()()".
Code: Python, Java, C++
1class Solution:
2 def removeOuterParentheses(self, s: str) -> str:
3 result = []
4 depth = 0
5 for ch in s:
6 if ch == '(':
7 if depth > 0:
8 result.append(ch)
9 depth += 1
10 else:
11 depth -= 1
12 if depth > 0:
13 result.append(ch)
14 return "".join(result)1class Solution {
2 public String removeOuterParentheses(String s) {
3 StringBuilder result = new StringBuilder();
4 int depth = 0;
5 for (char ch : s.toCharArray()) {
6 if (ch == '(') {
7 if (depth > 0) result.append(ch);
8 depth++;
9 } else {
10 depth--;
11 if (depth > 0) result.append(ch);
12 }
13 }
14 return result.toString();
15 }
16}1class Solution {
2public:
3 string removeOuterParentheses(string s) {
4 string result;
5 int depth = 0;
6 for (char ch : s) {
7 if (ch == '(') {
8 if (depth > 0) result += ch;
9 depth++;
10 } else {
11 depth--;
12 if (depth > 0) result += ch;
13 }
14 }
15 return result;
16 }
17};Time and space complexity
O(n)
Each character is read once and either appended or skipped in constant time.
O(n)
The output can hold up to n - 2 characters. Apart from the output, only one counter is used.
Other approaches
Explicit stack (time O(n), space O(n))
Push each ( and pop on each ). A ( pushed onto an empty stack, or a ) that empties it, is an outer character. It is the same rule as the depth counter, with the stack size playing the role of depth.
Find primitives, then slice (time O(n), space O(n))
Track the balance and remember where each primitive starts. When the balance returns to 0 at index i, append s[start + 1 : i]. It reads naturally from the problem statement and is also linear.
Common mistakes
- Updating the depth before checking it for
(. The outer(would then see depth 1 and be kept. - Checking the depth before decrementing it for
). The outer)would see depth 1 and be kept. - Building the answer with repeated string concatenation in a language where strings are immutable, which can turn the loop quadratic. Use a list, StringBuilder or byte slice.
- Assuming each primitive is just
(+ something +)with no nested primitives inside. Nesting depth, not position, decides what is outer.
Frequently asked questions
What is a primitive parentheses string?
A non-empty valid string that cannot be split into two non-empty valid strings. In a left-to-right scan, it is the stretch from a ( at depth 0 to the next point where the depth returns to 0.
Why does a depth counter work instead of a stack?
There is only one bracket type, so the stack would hold nothing but ( characters. Its size is all that matters, and an integer tracks that.
Can the result be empty?
Yes. If every primitive is a bare (), as in ()(), each one loses both characters and the answer is the empty string.
What is the time complexity of Remove Outermost Parentheses?
O(n) time, with O(n) space for the returned string and O(1) extra space for the depth counter.