#1021
Remove Outermost Parentheses
EasyStringStackStackTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach involves a single pass through the string while maintaining a balance counter. This allows us to directly construct the result without needing to track each primitive substring separately.
⚙️
Algorithm
5 steps- 1Step 1: Initialize an empty result string and a balance counter.
- 2Step 2: Iterate through the string, adjusting the balance for each '(' and ')'.
- 3Step 3: Skip the first '(' and the last ')' of each primitive substring by checking the balance.
- 4Step 4: Append valid characters to the result.
- 5Step 5: Return the result string.
solution.py13 lines
1def removeOuterParentheses(s):
2 result = ''
3 balance = 0
4 for char in s:
5 if char == '(':
6 if balance > 0:
7 result += char
8 balance += 1
9 else:
10 balance -= 1
11 if balance > 0:
12 result += char
13 return resultℹ
Complexity note: This complexity is linear because we traverse the string once, and the space complexity is linear due to the result string being built.
- 1Understanding the structure of valid parentheses strings is crucial.
- 2Recognizing the balance of parentheses helps in identifying primitive substrings.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.