Skip to content

Commit 03c7727

Browse files
committed
Remove outer most parantheses
1 parent 67de492 commit 03c7727

File tree

4 files changed

+139
-0
lines changed

4 files changed

+139
-0
lines changed
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
# 1021. Remove Outermost Parentheses
2+
3+
**Difficulty:** *Easy*
4+
**Category:** *Strings, Stack, Greedy*
5+
**Leetcode Link:** [Problem Link](https://leetcode.com/problems/remove-outermost-parentheses/)
6+
7+
---
8+
9+
## 📝 Introduction
10+
11+
*Given a valid parentheses string, the task is to remove the outermost parentheses of every primitive substring. A primitive string is a non-empty valid parentheses string that cannot be split further into valid parts.*
12+
13+
---
14+
15+
## 💡 Approach & Key Insights
16+
17+
*Each primitive parentheses string is balanced and starts/ends with outermost parentheses. If we track the nesting level using a counter, we can easily identify the start and end of each primitive and skip appending the outermost layer.*
18+
19+
---
20+
21+
## 🛠️ Breakdown of Approaches
22+
23+
### 1️⃣ Brute Force / Naive Approach
24+
25+
- **Explanation:** *Use a stack to build substrings for each primitive, detect primitives by ensuring stack becomes empty, then remove the first and last characters.*
26+
- **Time Complexity:** *O(n²) - Substring operations inside loop.*
27+
- **Space Complexity:** *O(n) - For temporary stack and result string.*
28+
- **Example/Dry Run:**
29+
30+
Example input: "(()())(())"
31+
Step 1 → Extract primitives: "(()())", "(())"
32+
Step 2 → Remove outermost: "()()", "()"
33+
Step 3 → Output: "()()()"
34+
35+
### 2️⃣ Optimized Approach
36+
37+
- **Explanation:** *Use a counter to track the nesting depth. While iterating, append characters only if they’re not the outermost (i.e., depth > 1 before ‘)’ or after ‘(’).*
38+
- **Time Complexity:** *O(n) - Single pass over string.*
39+
- **Space Complexity:** *O(n) - For output string.*
40+
- **Example/Dry Run:**
41+
42+
Example input: "(()())(())"
43+
Step 1 → Traverse:
44+
- ‘(’: depth becomes 1 → don’t add
45+
- ‘(’: depth becomes 2 → add ‘(’
46+
- ‘)’: depth becomes 1 → add ‘)’
47+
- ‘)’: depth becomes 0 → don’t add
48+
... and so on
49+
Output: "()()()"
50+
51+
---
52+
53+
## 📊 Complexity Analysis
54+
55+
| Approach | Time Complexity | Space Complexity |
56+
| ------------- | --------------- | ---------------- |
57+
| Brute Force | O(n²) | O(n) |
58+
| Optimized | O(n) | O(n) |
59+
60+
---
61+
62+
## 📉 Optimization Ideas
63+
64+
*The optimized solution is already linear in time and space. Further improvement would require in-place modification or custom output building if language permits.*
65+
66+
---
67+
68+
## 📌 Example Walkthroughs & Dry Runs
69+
70+
```plaintext
71+
Example:
72+
Input: "(()())(())(()(()))"
73+
Process:
74+
Primitive 1: "(()())" → Output: "()()"
75+
Primitive 2: "(())" → Output: "()"
76+
Primitive 3: "(()(()))" → Output: "()(())"
77+
Final Output: "()()()()(())"
78+
```
79+
80+
---
81+
82+
## 🔗 Additional Resources
83+
84+
- [Stack Data Structure](https://en.wikipedia.org/wiki/Stack_(abstract_data_type))
85+
- [Valid Parentheses Leetcode](https://leetcode.com/problems/valid-parentheses/)
86+
87+
---
88+
89+
Author: Abdul Wahab
90+
Date: 19/07/2025
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
class Solution {
2+
public:
3+
string removeOuterParentheses(string s) {
4+
string res;
5+
int balance = 0, start = 0;
6+
for (int i = 0; i < s.length(); ++i) {
7+
if (s[i] == '(') balance++;
8+
else balance--;
9+
if (balance == 0) {
10+
res += s.substr(start + 1, i - start - 1);
11+
start = i + 1;
12+
}
13+
}
14+
return res;
15+
}
16+
};
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Solution {
2+
public String removeOuterParentheses(String s) {
3+
int sum = 0, start = 0, end = 0;
4+
StringBuilder res = new StringBuilder();
5+
6+
while (end < s.length()) {
7+
if (s.charAt(end) == '(') sum++;
8+
else sum--;
9+
10+
if (sum == 0) {
11+
res.append(s.substring(start + 1, end)); // exclude outer
12+
start = end + 1;
13+
}
14+
end++;
15+
}
16+
return res.toString();
17+
}
18+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
class Solution:
2+
def removeOuterParentheses(self, s: str) -> str:
3+
res = []
4+
balance = 0
5+
start = 0
6+
7+
for i, ch in enumerate(s):
8+
if ch == '(':
9+
balance += 1
10+
else:
11+
balance -= 1
12+
if balance == 0:
13+
res.append(s[start + 1:i])
14+
start = i + 1
15+
return ''.join(res)

0 commit comments

Comments
 (0)