Skip to content
thesarfo

Reference

Remove Outermost Parentheses

Stripping the outermost parentheses from each primitive substring of a valid parentheses string using a depth counter.

views 0

Given a valid parentheses string composed of multiple primitive valid substrings, remove the outermost parentheses from each primitive substring while leaving the rest of the structure unchanged. A primitive valid parentheses string is a non-empty valid substring that can’t be split further into smaller valid parts — e.g. in "(()())(())", "(()())" and "(())" are the two primitive parts. (LeetCode 1021)

Approach: iterate through the string, tracking nesting depth with a counter (parenthesesCount) — increment on '(', decrement on ')'. Only append '(' to the result if it’s not the first character of its primitive substring (i.e., parenthesesCount > 0 before incrementing), and only append ')' if it’s not the last (parenthesesCount > 0 after decrementing).

class Solution {
public String removeOuterParentheses(String s) {
StringBuilder result = new StringBuilder(); // To store final output
int parenthesesCount = 0; // Tracks nested level
for (int i = 0; i < s.length(); i++) {
char currentChar = s.charAt(i);
if (currentChar == '(') {
if (parenthesesCount > 0) { // Ignore outermost '('
result.append(currentChar);
}
parenthesesCount++; // Increase count for nested '('
} else { // If currentChar is ')'
parenthesesCount--; // Decrease count for closing ')'
if (parenthesesCount > 0) { // Ignore outermost ')'
result.append(currentChar);
}
}
}
return result.toString();
}
}

For s = "(()())(())", tracing through: the first ( (count 0→1) is ignored as outermost, the next ( (count 1→2) is added, and so on — the first ( and last ) of each primitive substring get dropped while everything else is kept, producing "()()()".

Time: O(n). Space: O(n) for the StringBuilder.