question_slug
stringlengths
3
77
title
stringlengths
1
183
slug
stringlengths
12
45
summary
stringlengths
1
160
author
stringlengths
2
30
certification
stringclasses
2 values
created_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
updated_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
hit_count
int64
0
10.6M
has_video
bool
2 classes
content
stringlengths
4
576k
upvotes
int64
0
11.5k
downvotes
int64
0
358
tags
stringlengths
2
193
comments
int64
0
2.56k
remove-outermost-parentheses
Java♨️ || 2 Approaches(With+Without Stack) ✅
java-2-approacheswithwithout-stack-by-ri-f5lj
The main thing is --> (()()) --> If the stack(or counter) is greater than 1 then include "(" and ")" in answer else don\'t include as we need to remove outermos
Ritabrata_1080
NORMAL
2022-09-21T21:56:28.922615+00:00
2022-10-25T09:28:36.289669+00:00
1,577
false
**The main thing is --> (()()) --> If the stack(or counter) is greater than 1 then include "(" and ")" in answer else don\'t include as we need to remove outermost parenthesis... If you find the solution helpful please upvote :)**\n\n**Without stack approach -->**\n```\nclass Solution {\n public String removeOuterParentheses(String s) {\n StringBuilder sb = new StringBuilder();\n int level = 0;\n for(int i = 0;i<s.length();i++){\n if(s.charAt(i) == \'(\'){\n level++;\n }\n if(level > 1){\n sb.append(s.charAt(i));\n }\n if(s.charAt(i) == \')\'){\n level--;\n }\n }\n return sb.toString();\n }\n}\n```\n\n\n**With Stack Approach-->**\n```\nclass Solution {\n public String removeOuterParentheses(String s) {\n StringBuilder sb = new StringBuilder();\n Stack<Character> st = new Stack<>();\n for(char c : s.toCharArray()){\n if(st.isEmpty() && c == \'(\'){\n st.push(\'(\');\n }\n else if(!st.isEmpty() && c == \'(\'){\n st.push(c);\n sb.append(c);\n }\n else if(st.size() >1 && c == \')\'){\n st.pop();\n sb.append(c);\n }\n else if(st.size() == 1 && c == \')\'){\n st.pop();\n }\n }\n return sb.toString();\n }\n}\n\n```
12
0
['Stack', 'Java']
0
remove-outermost-parentheses
Java in 6 lines
java-in-6-lines-by-silviodp3-y06z
\nclass Solution {\n public String removeOuterParentheses(String s) {\n \n int count = 0;\n\t\tStringBuilder sb = new StringBuilder();\n\t\t\n\
silviodp3
NORMAL
2019-06-09T03:13:28.330331+00:00
2019-06-09T03:13:28.330395+00:00
1,801
false
```\nclass Solution {\n public String removeOuterParentheses(String s) {\n \n int count = 0;\n\t\tStringBuilder sb = new StringBuilder();\n\t\t\n\t\tfor (char c : s.toCharArray()) {\n\n\t\t\tif (c == \'(\' && count++ > 0) { sb.append(c); }\n\t\t\tif (c == \')\' && --count > 0) { sb.append(c); }\n\t\t\t\n\t\t}\n\t\t\n\t\treturn sb.toString();\n }\n}\n```
12
0
[]
3
remove-outermost-parentheses
Simple O(n) Java solution
simple-on-java-solution-by-hobiter-2hdg
Thanks to fengyunzhe90.\n\n```\nclass Solution {\n public String removeOuterParentheses(String s) {\n Stack stack = new Stack<>();\n \n
hobiter
NORMAL
2019-04-07T05:50:15.890058+00:00
2019-04-07T05:50:15.890147+00:00
1,354
false
Thanks to fengyunzhe90.\n\n```\nclass Solution {\n public String removeOuterParentheses(String s) {\n Stack<Character> stack = new Stack<>();\n \n String result = "";\n \n for (int i = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n \n if (stack.isEmpty() && c == \'(\') {\n stack.push(c);\n continue;\n }\n \n if (stack.size() == 1 && c == \')\') {\n stack.pop();\n continue;\n }\n \n if (c == \'(\') {\n stack.push(c);\n }\n \n if (c == \')\') {\n stack.pop();\n }\n result += c + "";\n }\n\n return result;\n }\n} ;
12
0
[]
1
remove-outermost-parentheses
Easy and Simple Approach ✅ || Beats 100% 🎯
easy-and-simple-approach-beats-100-by-rc-ju0a
\n# Code\n\nclass Solution {\npublic:\n string removeOuterParentheses(string s) {\n string ans;\n int cnt = 0;\n for (char chr : s)\n
rckrockerz
NORMAL
2024-05-23T04:57:46.982511+00:00
2024-06-12T15:12:09.654368+00:00
1,656
false
![image.png](https://assets.leetcode.com/users/images/0669a34b-4fbf-451f-a8ba-069539c39539_1716463256.564444.png)\n# Code\n```\nclass Solution {\npublic:\n string removeOuterParentheses(string s) {\n string ans;\n int cnt = 0;\n for (char chr : s)\n if (chr == \'(\')\n if (!cnt)\n cnt++;\n else {\n ans += \'(\';\n cnt++;\n }\n else if (cnt > 1) {\n ans += \')\';\n cnt--;\n } else\n cnt--;\n return ans;\n }\n};\n```
11
0
['String', 'Stack', 'C++']
1
remove-outermost-parentheses
JAVA }} O(n) || Easy Approach With comment
java-on-easy-approach-with-comment-by-sw-vykt
\nclass Solution\n{\n public String removeOuterParentheses(String S) \n {\n Stack<Character> valid=new Stack<>();//checking the balance and when th
swapnilGhosh
NORMAL
2021-06-26T08:40:25.533566+00:00
2021-06-26T08:41:03.511772+00:00
1,486
false
```\nclass Solution\n{\n public String removeOuterParentheses(String S) \n {\n Stack<Character> valid=new Stack<>();//checking the balance and when the stack is Empty\n List<Integer> index=new ArrayList<>();//for storing the index\n char ch;\n \n for(int i=0;i<S.length();i++)//traversering the indices \n {\n ch=S.charAt(i);//extracting charracter\n if(valid.isEmpty())//new valid parentheses \n {\n valid.push(ch);//pushing it into the stack the open parentheses \n index.add(i);//and pushing it corresponding index \n }\n else if(ch==\')\'&&valid.peek()==\'(\')\n {\n valid.pop();\n if(valid.isEmpty())//ending of new valid parentheses\n index.add(i);//storing the closing index \n }\n else\n {\n valid.push(ch);//otherwise pushing he open parentheses \n }\n }\n StringBuilder res=new StringBuilder();//resultant \n for(int i=0;i<index.size();i+=2)//index is always in pair i.e;starting and ending \n {\n res.append(S.substring(index.get(i)+1,index.get(i+1)));//removing the outmost parenthesis for the given pair of indices \n }\n return res.toString();//returning the String \n }\n}//Please do vote me, It helps a lot\n```
11
0
['Stack', 'Java']
0
remove-outermost-parentheses
0 ms C++ Approach
0-ms-c-approach-by-akashrajakku-m711
Intuition\n Describe your first thoughts on how to solve this problem. \nA valid string has equal number of \'(\' and \')\' braces. So if we keep count of numbe
akashrajakku
NORMAL
2024-01-23T06:00:38.497829+00:00
2024-01-23T06:00:38.497855+00:00
1,298
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nA valid string has equal number of \'(\' and \')\' braces. So if we keep count of number of opening and closing braces, we can check for a valid parenthesis easily.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe took a count variable and incremented its value by 1 when found \'(\' and decremented its value by 1 when found \')\'. Now if our count variable has value 1 and we are on \'(\' , this means it is our outermost parenthesis and it should not be included in our answer. Similarily if count variable has value 0 and our iterator is pointing to \')\', this means this is a closing outer parenthesis , so it will be ignored. And for all other cases we update our result.\n\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n string removeOuterParentheses(string s) {\n string res="";\n int count=0;\n int size=s.size();\n for(int i=0;i<size;i++){\n if(s[i]==\'(\')\n count++;\n else\n count--;\n \n if((count==1 && s[i]==\'(\') || (count==0 && s[i]==\')\')) \n continue;\n else\n res+=s[i];\n }\n return res;\n }\n};\n```
10
0
['C++']
2
remove-outermost-parentheses
stack java
stack-java-by-niyazjava-kd56
If you like it pls upvote\n\n\n public String removeOuterParentheses(String s) {\n Stack<Character> st = new Stack<>();\n StringBuilder sb = ne
NiyazJava
NORMAL
2022-11-01T09:17:12.855279+00:00
2022-11-07T17:31:29.826661+00:00
1,821
false
If you like it pls upvote\n```\n\n public String removeOuterParentheses(String s) {\n Stack<Character> st = new Stack<>();\n StringBuilder sb = new StringBuilder();\n\n for (int i = 0; i < s.length(); i++) {\n if (s.charAt(i) == \'(\') {\n if (st.size() >= 1) {\n sb.append(s.charAt(i));\n }\n st.push(s.charAt(i));\n } else {\n if (st.size() > 1) {\n sb.append(s.charAt(i));\n }\n st.pop();\n }\n }\n return sb.toString();\n }\n\n```
10
0
['Stack', 'Java']
2
remove-outermost-parentheses
Clean JavaScript Solution
clean-javascript-solution-by-shimphillip-d2c0
\n// time O(n) space O(n)\nvar removeOuterParentheses = function(S) {\n let result = \'\'\n let level = 0\n \n for(const item of S) {\n if(it
shimphillip
NORMAL
2020-10-29T21:01:32.824440+00:00
2020-11-13T19:08:44.768081+00:00
1,097
false
```\n// time O(n) space O(n)\nvar removeOuterParentheses = function(S) {\n let result = \'\'\n let level = 0\n \n for(const item of S) {\n if(item === \')\') {\n level--\n }\n if(level >= 1) {\n result += item \n }\n if(item === \'(\') {\n level++\n }\n }\n \n return result\n};\n```
10
0
['JavaScript']
0
remove-outermost-parentheses
C++ solution using stack
c-solution-using-stack-by-sat5683-c270
```class Solution {\npublic:\n string removeOuterParentheses(string S) {\n string result="";\n stack st;\n for(auto ch : S){\n
sat5683
NORMAL
2019-04-08T18:14:04.352162+00:00
2019-04-08T18:14:04.352209+00:00
740
false
```class Solution {\npublic:\n string removeOuterParentheses(string S) {\n string result="";\n stack<char> st;\n for(auto ch : S){\n if(ch==\'(\'){\n if(st.size()>0){\n result+=ch;\n }\n st.push(ch);\n }\n else{\n if(st.size()>1){\n result+=ch;\n }\n st.pop();\n }\n }\n return result;\n }\n};
10
1
['Stack']
0
remove-outermost-parentheses
Easy solution 🚀| Detailed explanation☑️☑️ | Beginner friendly 📍|
easy-solution-detailed-explanation-begin-k7wp
Approach\n1. Initialization:\n\n- Initialize an empty string ans to store the result.\n2. Iterating Over Characters:\n\n- We will Iterate through each character
Prabhakar_s_kulkarni
NORMAL
2024-02-28T05:55:57.207355+00:00
2024-02-28T05:56:39.196543+00:00
713
false
# Approach\n1. Initialization:\n\n- Initialize an empty string ans to store the result.\n2. Iterating Over Characters:\n\n- We will Iterate through each character ch in the input string s.\n3. Tracking Parentheses Count:\n\n- Maintain a variable count to keep track of the current nesting level of parentheses.\n- When encountering an opening parenthesis \'(\' and the count is 0, increment the count and ignore adding this parenthesis to the result since it\'s the outermost one.\n- When encountering an opening parenthesis \'(\' and the count is greater than or equal to 1, increment the count and append the parenthesis to the result. This represents an inner parenthesis.\n- When encountering a closing parenthesis \')\' and the count is greater than 1, append the parenthesis to the result and decrement the count. This represents an inner parenthesis.\n- When encountering a closing parenthesis \')\' and the count is exactly 1, decrement the count without appending to the result, as it represents the outermost closing parenthesis.\n4. Return Result:\n\n- Lastly return the string ans, which contains the desired string without the outermost parentheses.\n\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n string removeOuterParentheses(string s) {\n // int n = s.size();\n string ans="";\n int count = 0;\n for(char ch:s)\n {\n if(ch==\'(\' && count==0)\n {\n count++;\n }\n else if(ch==\'(\' && count>=1)\n {\n ans = ans + ch;\n count++;\n }\n else if(ch==\')\' && count>1)\n {\n ans = ans + ch;\n count--;\n }\n else if(ch==\')\' && count==1)\n {\n count--;\n }\n }\n return ans;\n }\n};\n```\n\n![upvote.jpg](https://assets.leetcode.com/users/images/a44dc151-0b0a-449f-896e-7d4915b38b37_1709099735.465367.jpeg)\n
9
0
['String', 'C++']
1
remove-outermost-parentheses
C++ 0ms shortest code
c-0ms-shortest-code-by-nikunjdaskasat-dkx3
\nclass Solution {\npublic:\n string removeOuterParentheses(string S) {\n stack<char> st;\n string ans;\n for(char c: S)\n {\n
nikunjdaskasat
NORMAL
2020-12-19T09:26:51.973833+00:00
2020-12-19T09:26:51.973865+00:00
613
false
```\nclass Solution {\npublic:\n string removeOuterParentheses(string S) {\n stack<char> st;\n string ans;\n for(char c: S)\n {\n if(c == \')\') st.pop();\n if(!st.empty()) ans += c;\n if(c == \'(\') st.push(c);\n }\n return ans;\n }\n};\n```
9
1
['Stack', 'C']
0
remove-outermost-parentheses
JavaScript counter solution
javascript-counter-solution-by-kremenher-f0o2
\n/**\n * @param {string} S\n * @return {string}\n */\nvar removeOuterParentheses = function(S) {\n let counter = 0;\n let result = \'\';\n \n for (
kremenhero
NORMAL
2019-04-07T16:24:17.982440+00:00
2019-04-07T16:24:17.982484+00:00
1,694
false
```\n/**\n * @param {string} S\n * @return {string}\n */\nvar removeOuterParentheses = function(S) {\n let counter = 0;\n let result = \'\';\n \n for (let i = 0; i < S.length; i++) {\n if ((S[i] === \'(\' && ++counter !== 1) || (S[i] === \')\' && --counter !== 0)) {\n result += S[i];\n }\n }\n \n return result;\n};\n```
9
1
['JavaScript']
3
remove-outermost-parentheses
Easy C++ Solution || Beginner Friendly ✅✅
easy-c-solution-beginner-friendly-by-man-5xbw
\n# Approach\nThis question is all about the counter. As the very first bracket would start from 0 and thus that will not be included and the last outermost bra
Manisha_jha658
NORMAL
2023-08-10T14:34:55.319187+00:00
2023-08-10T14:50:50.387810+00:00
1,373
false
\n# Approach\nThis question is all about the counter. As the very first bracket would start from 0 and thus that will not be included and the last outermost bracket with value 0 will also be not included.\n\nIn this way we will check whether the char should be added into the string or not. \nAdd 1 if there is \'(\' open parenthesis. and sub 1 if \')\' clsed paranthesis.\n\nFor eg.\n \n![01.png](https://assets.leetcode.com/users/images/0aec98a5-dfdc-452d-9417-ad1e1bacf6eb_1691679008.493465.png)\n\n\nIn above explanation, wherever the count is zero. We are not adding that in string.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\npublic:\n string removeOuterParentheses(string s) {\n string ans="";\n int c=0;\n for(char ch:s){\n if(ch==\'(\' && c==0){\n //skip, as this would be the first bracket so it will be considered as outermost bracket\n c++;\n }\n else if(ch==\'(\' && c>=1){\n ans+=ch;\n c++;\n //add ch in the string\n }\n else if(ch==\')\' && c>1){\n //sub ch in the string, as it\'s pair is alrrady added\n ans+=ch;\n c--;\n }\n else if(ch==\')\' && c==1){\n //skip it, outermost bracket\n c--;\n }\n }\n return ans;\n }\n};\n```
8
0
['C++']
5
remove-outermost-parentheses
C++✅✅| Beats 100% | self-Explained🔥 | Beginner Friendly Approach✔ | Clean Code |stack
c-beats-100-self-explained-beginner-frie-v9px
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
Rhythm_1383
NORMAL
2023-08-07T11:04:48.152601+00:00
2023-08-07T11:04:48.152620+00:00
1,392
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n string removeOuterParentheses(string s) {\n string result;\n stack <char> st;\n for(int i:s)\n {\n if(i==\'(\')\n {\n if(!st.empty())\n {\n result.push_back(i);\n }\n st.push(i);\n }\n else{\n st.pop();\n if(!st.empty())\n {\n result.push_back(i);\n }\n }\n \n }\n return result;\n }\n};\n```
8
0
['Stack', 'C++']
1
remove-outermost-parentheses
C++ and C# very easy solution.
c-and-c-very-easy-solution-by-aloneguy-0cz9
Intuition:First of all,we have to find outer parentheses and after that we have to add other parentheses to a new string.\n Describe your first thoughts on how
aloneguy
NORMAL
2023-04-10T00:43:32.355092+00:00
2023-04-10T00:43:32.355126+00:00
2,602
false
# Intuition:First of all,we have to find outer parentheses and after that we have to add other parentheses to a new string.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach:Each pair has a couple of parenthese.So we use stack to declare which parenthese is either opener or cleser.\n<!-- Describe your approach to solving the problem. -->\n![photo_2023-04-10_05-40-10.jpg](https://assets.leetcode.com/users/images/399e55fc-74f8-4ba0-809c-086907be6e71_1681087371.7124531.jpeg)\n\n\n```C++ []\nclass Solution {\npublic:\n string removeOuterParentheses(string s) {\n string result;\n int index = 0;\n for (char x : s) {\n switch(x){\n case \'(\':\n if(index++>0)result+=x;\n break;\n case \')\':\n if(index-->1)result+=x;\n break;\n }\n }\n return result;\n }\n};\n```\n```C# []\npublic class Solution {\n public string RemoveOuterParentheses(string s) {\n StringBuilder result=new();\n int index = 0;\n foreach (char x in s) {\n if (x == \'(\' && index++ > 0) \n result.Append(x);\n else if (x == \')\' && index-- > 1) \n result.Append(x);\n }\n return result.ToString();\n }\n}\n```\n
8
0
['String', 'Stack', 'C++', 'C#']
0
remove-outermost-parentheses
✅ C++ 2 solutions: stack & counter
c-2-solutions-stack-counter-by-yespower-xuk3
Solution 1 : Use std::stackIntuitionTo solve this problem, we can keep track of the outer parentheses using a stack. Whenever we encounter an open parenthesis,
yespower
NORMAL
2020-03-02T06:51:49.362046+00:00
2025-02-26T20:40:08.065574+00:00
905
false
# Solution 1 : Use std::stack ## Intuition To solve this problem, we can keep track of the outer parentheses using a stack. Whenever we encounter an open parenthesis, we push it onto the stack. When we encounter a close parenthesis, we pop an open parenthesis from the stack. We only add the current character to our result string when the stack is not empty. ## Approach 1 Initialize an empty stack and an empty result string. 2. Iterate through the input string: a. If the stack is not empty, add the current character to the result string. b. If the current character is an open parenthesis, push it onto the stack. c. If the current character is a close parenthesis, pop an open parenthesis from the stack. If the stack is now empty, remove the last character from the result string. 3. Return the result string. ## Complexity - Time complexity: $$O(n)$$, where n is the length of the input string. We iterate through the entire string once. - Space complexity: $$O(n)$$, as in the worst case (e.g., all open parentheses), the stack could store all characters in the input string. # Code ``` class Solution { public: string removeOuterParentheses(string s) { std::stack<char> stack; std::string r; for(auto c: s){ if(!stack.empty()) { r += c; } if(c == '(') { stack.push(c); } else { stack.pop(); if(stack.empty()) { r.pop_back(); } } } return r; } }; ``` # Solution 2 : Use a counter ## Intuition An alternative to using a stack is to simply maintain a count of the open parentheses encountered. We can increment the count when we encounter an open parenthesis and decrement it when we encounter a close parenthesis. ## Approach 1. Initialize an empty result string and a count variable set to 0. 2. Iterate through the input string: a. If the current character is an open parenthesis and the count is greater than 0, add the current character to the result string and increment the count. b. If the current character is a close parenthesis and the count is greater than 1, add the current character to the result string and decrement the count. 3. Return the result string. ## Complexity - Time complexity: $$O(n)$$, where n is the length of the input string. We iterate through the entire string once. - Space complexity: $$O(n)$$, since the result string could store up to n-2 characters (e.g., if the input string has only one pair of outer parentheses). # Code ``` class Solution { public: string removeOuterParentheses(string s) { std::string r; int count = 0; for(char c : s){ if(c == '(' && count++ > 0) r += c; if(c == ')' && count-- > 1) r += c; } return r; } }; ```
8
0
['C', 'C++']
0
remove-outermost-parentheses
simple and easy Python solution 😍❤️‍🔥
simple-and-easy-python-solution-by-shish-k8ml
\n\n\n# if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n###### Let\'s Connect on LinkedIn: www.linkedin.com/in/shishirrsiam\n###### Let\'s Connect on Face
shishirRsiam
NORMAL
2024-08-21T03:37:59.168148+00:00
2024-08-21T03:37:59.168172+00:00
1,266
false
\n\n\n# if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n###### Let\'s Connect on LinkedIn: www.linkedin.com/in/shishirrsiam\n###### Let\'s Connect on Facebook: www.fb.com/shishirrsiam\n\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python []\nclass Solution(object):\n def removeOuterParentheses(self, s):\n ans = \'\'\n cnt = 0\n for ch in s:\n if ch == \'(\':\n if cnt:\n ans += ch\n cnt += 1\n else:\n cnt -= 1\n if cnt:\n ans += ch\n return ans\n```
7
0
['String', 'Stack', 'Python', 'Python3']
3
remove-outermost-parentheses
✅C++|| Stack And Without Stack || Easy Solution
c-stack-and-without-stack-easy-solution-dxyj8
Approach 1: (Stack) \u2705\n\nC++\n\nclass Solution {\npublic:\n\nstring removeOuterParentheses(string S) {\n stack<char>st;\n string ans;\n for(auto a
indresh149
NORMAL
2022-10-19T06:58:45.148934+00:00
2022-10-19T06:58:45.148972+00:00
1,286
false
**Approach 1: (Stack) \u2705**\n\n**C++**\n```\nclass Solution {\npublic:\n\nstring removeOuterParentheses(string S) {\n stack<char>st;\n string ans;\n for(auto a:S)\n {\n if(a==\'(\')\n {\n if(st.size()>0)\n {\n ans+=\'(\';\n }\n st.push(\'(\');\n }\n else\n {\n if(st.size()>1)\n {\n ans+=\')\';\n }\n st.pop();\n }\n }\n return ans;\n}\n};\n```\n**Java**\n```\nclass Solution {\n public String removeOuterParentheses(String s) {\n Stack<Character> st = new Stack<>();\n StringBuilder sb = new StringBuilder();\n \n for(int i=0;i<s.length();i++){\n char ch = s.charAt(i);\n \n if(ch == \'(\'){\n if(st.size() > 0){\n sb.append(ch);\n }\n st.push(ch);\n }\n else\n {\n st.pop();\n if(st.size() > 0){\n sb.append(ch);\n }\n }\n }\n return sb.toString();\n }\n}\n```\n\n**Approach 2: (Without Stack ) \u2705**\n\n**C++**\n```\nclass Solution {\npublic:\n\nstring removeOuterParentheses(string S) {\n int st=0;\n string ans;\n for(auto a:S)\n {\n if(a==\'(\')\n {\n if(st>0)\n {\n ans+=\'(\';\n }\n st++;\n }\n else\n {\n if(st>1)\n {\n ans+=\')\';\n }\n st--;\n }\n }\n return ans;\n}\n};\n```\n**Java**\n```\nclass Solution {\n public String removeOuterParentheses(String S) {\n StringBuilder sb = new StringBuilder();\n int counter = 0;\n for(char c : S.toCharArray()){\n if(c == \'(\'){\n if(counter != 0) sb.append(c);\n counter++;\n }\n else{\n counter--;\n if(counter != 0) sb.append(c);\n }\n }\n \n return sb.toString();\n }\n}\n```\n
7
0
['String', 'Stack', 'C']
1
remove-outermost-parentheses
Remove Outermost Parentheses|| cpp|| easy way
remove-outermost-parentheses-cpp-easy-wa-9vzf
\n\nclass Solution {\npublic:\n string removeOuterParentheses(string s) {\n int count = 0;\n string ans = "";\n for(int i=0;i0){\n
shraddha1517
NORMAL
2022-09-26T16:41:02.248109+00:00
2022-09-26T16:41:02.248137+00:00
1,388
false
```\n```\nclass Solution {\npublic:\n string removeOuterParentheses(string s) {\n int count = 0;\n string ans = "";\n for(int i=0;i<s.length();i++){\n if( s[i]==\'(\' && count == 0){\n count++;\n }\n else\n if(s[i]==\'(\' && count>0){\n count++;\n ans+=s[i];\n }\n else if(s[i]==\')\'){\n count--;\n if(count>0)ans+=s[i];\n } \n }\n return ans;\n \n }\n};\n```\n```
7
0
[]
0
remove-outermost-parentheses
java two solution 1. using stack 2.simple for loop
java-two-solution-1-using-stack-2simple-db033
using Stack\n\nclass Solution {\n public String removeOuterParentheses(String S) {\n Stack<Character> st=new Stack();\n StringBuilder sb=new St
va_asu_
NORMAL
2021-06-04T04:45:04.082067+00:00
2021-06-04T04:45:04.082113+00:00
1,028
false
using Stack\n```\nclass Solution {\n public String removeOuterParentheses(String S) {\n Stack<Character> st=new Stack();\n StringBuilder sb=new StringBuilder();\n for(char ch:S.toCharArray())\n {\n if(ch==\'(\')\n {\n if(st.size()>=1)\n {\n sb.append(ch);\n }\n st.push(ch);\n }\n else{\n if(st.size()>1)\n {\n sb.append(ch);\n }\n st.pop();\n }\n }\n return sb.toString();\n }\n}\n```\n\nusing Array\n```\nclass Solution {\n public String removeOuterParentheses(String S) {\n int top=-1;\n String str="";\n for(int i=0;i<S.length()-1;i++){\n \n if(S.charAt(i)==\'(\'&&++top!=0)\n {\n str+=S.charAt(i);\n }\n else if(S.charAt(i)==\')\'&&--top!=-1)\n {\n str+=S.charAt(i);\n }\n \n }\n return str;\n }\n}\n```
7
0
['Stack', 'Java']
0
remove-outermost-parentheses
Python Simplest Solution
python-simplest-solution-by-aishwaryanat-pfic
\nclass Solution:\n def removeOuterParentheses(self, S: str) -> str:\n \n stack=[]\n counter=0\n for i in S:\n if i==\
aishwaryanathanii
NORMAL
2021-04-17T04:05:40.427888+00:00
2021-04-17T04:05:40.427930+00:00
653
false
```\nclass Solution:\n def removeOuterParentheses(self, S: str) -> str:\n \n stack=[]\n counter=0\n for i in S:\n if i==\'(\':\n counter=counter+1\n if counter==1:\n pass\n else:\n stack.append(i)\n else:\n counter=counter-1\n if counter == 0:\n pass\n else:\n stack.append(i)\n return (\'\'.join(stack))\n```\n\nDo upvote \uD83D\uDC4D if you like and understand my approach!
7
0
['Python', 'Python3']
0
remove-outermost-parentheses
Easy and Simple Solution
easy-and-simple-solution-by-mayankluthya-yt1l
Please Like ❤️IntuitionTo remove the outermost parentheses of each valid primitive string in a valid parentheses string, the approach revolves around maintainin
mayankluthyagi
NORMAL
2025-01-24T16:45:42.542113+00:00
2025-01-24T16:45:42.542113+00:00
1,056
false
```java class Solution { public String removeOuterParentheses(String s) { StringBuilder str = new StringBuilder(); int count = 0; for (char ch : s.toCharArray()) { if (ch == '(') { if (count > 0) str.append("("); count++; } else { count--; if (count > 0) str.append(")"); } } return str.toString(); } } ``` # Please Like ❤️ ![Please Like](https://media.tenor.com/heEyHbV8iaUAAAAM/puss-in-boots-shrek.gif) # Intuition To remove the outermost parentheses of each valid primitive string in a valid parentheses string, the approach revolves around maintaining a counter to track the depth of parentheses. # Approach 1. Use a counter `count` to track the depth of parentheses: - Increment the counter for each opening parenthesis `(`. - Decrement the counter for each closing parenthesis `)`. 2. Add characters to the result string only if they are not part of the outermost parentheses: - Append `(` to the result if `count > 0` before incrementing. - Append `)` to the result if `count > 0` after decrementing. # Complexity - **Time complexity**: $$O(n)$$, where $$n$$ is the length of the input string `s`, as we iterate through the string once. - **Space complexity**: $$O(n)$$, due to the usage of the `StringBuilder` to store the result.
6
0
['Java']
0
remove-outermost-parentheses
simple and easy Javascript solution 😍❤️‍🔥
simple-and-easy-javascript-solution-by-s-1z32
\n\n\n# if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n###### Let\'s Connect on LinkedIn: www.linkedin.com/in/shishirrsiam\n###### Let\'s Connect on Face
shishirRsiam
NORMAL
2024-08-21T03:40:14.206792+00:00
2024-08-21T03:40:14.206835+00:00
476
false
\n\n\n# if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n###### Let\'s Connect on LinkedIn: www.linkedin.com/in/shishirrsiam\n###### Let\'s Connect on Facebook: www.fb.com/shishirrsiam\n\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```javascript []\nvar removeOuterParentheses = function(s) \n{\n let ans = \'\'\n let cnt = 0\n for (ch of s)\n {\n if(ch === \'(\')\n {\n if(cnt) ans += ch;\n cnt++;\n }\n else \n {\n cnt--;\n if(cnt) ans += ch;\n }\n }\n return ans\n};\n```
6
0
['String', 'Stack', 'JavaScript']
3
remove-outermost-parentheses
✔️✔️✔️very easy solution - without STACK - beats 100%⚡⚡⚡PYTHON || C++
very-easy-solution-without-stack-beats-1-yozf
Code\nPython []\nclass Solution:\n def removeOuterParentheses(self, s: str) -> str:\n string = ""\n opened = 0\n for i in s:\n
anish_sule
NORMAL
2024-04-22T07:21:23.306497+00:00
2024-04-22T07:34:03.898510+00:00
897
false
# Code\n```Python []\nclass Solution:\n def removeOuterParentheses(self, s: str) -> str:\n string = ""\n opened = 0\n for i in s:\n if i == "(":\n opened += 1\n if opened > 1:\n string += i\n else:\n opened -= 1\n if opened > 0:\n string += i\n return string\n```\n```C++ []\nclass Solution {\npublic:\n string removeOuterParentheses(string s) {\n string fin = "";\n int opened = 0;\n for(auto i : s){\n if (i == \'(\'){\n opened++;\n if (opened > 1){\n fin.push_back(i);\n }\n }\n else{\n opened--;\n if (opened > 0){\n fin.push_back(i);\n }\n }\n }\n return fin;\n }\n};\n```
6
0
['String', 'C++', 'Python3']
0
remove-outermost-parentheses
Remove Outermost Parenthesis || Beats 100% || Java || Fully Explained
remove-outermost-parenthesis-beats-100-j-7hfv
Approach\n- The method starts by initializing a StringBuilder to construct the final result. Declare an int variable cnt to keep track of the number of open par
Vishu6403
NORMAL
2023-11-11T17:42:16.888335+00:00
2023-11-11T17:42:16.888362+00:00
913
false
# Approach\n- The method starts by initializing a StringBuilder to construct the final result. Declare an int variable `cnt` to keep track of the number of open parentheses encountered.\n- Iterate through each character of string s. Within the loop, the code checks if the current character is an opening parenthesis `\'(\'`.\n- If an opening parenthesis is encountered, check if there are already open parentheses (nested ones). If yes, add the current opening parenthesis to the result `(sb)`. Increment the count of open parentheses `(cnt)`.\n- If a closing parenthesis is encountered, check if there are still open parentheses (nested ones). If yes, add the current closing parenthesis to the result `(sb)`. Decrement the count of open parentheses` (cnt)`.\n- Return the result (sb).\n\n\n# Complexity\n- Time complexity:$$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public String removeOuterParentheses(String s) {\n StringBuilder sb = new StringBuilder();\n int cnt = 0;\n\n for (char c : s.toCharArray()) {\n if (c == \'(\') {\n if (cnt > 0) {\n sb.append(c);\n }\n cnt++;\n } else if (c == \')\') {\n cnt--;\n if (cnt > 0) {\n sb.append(c);\n }\n }\n }\n\n return sb.toString();\n }\n}\n\n```
6
0
['String', 'Java']
0
remove-outermost-parentheses
c++ beats 100% ✅ | with explaination | O(n) time, O(1) space
c-beats-100-with-explaination-on-time-o1-bzin
Intuition\nOpening parenthesis decreases the counter and closing parenthesis increases the counter\n\n ( ( ) ( ) ) ( ( ) )\n0 -1 -2 -1 -2 -1 0 -1 -2 -1
vikas107sharma
NORMAL
2023-08-09T14:43:36.202660+00:00
2023-08-09T14:43:36.202685+00:00
417
false
# Intuition\nOpening parenthesis decreases the counter and closing parenthesis increases the counter\n```\n ( ( ) ( ) ) ( ( ) )\n0 -1 -2 -1 -2 -1 0 -1 -2 -1 0\n```\n\nThere is always a primitive string after a zero till next zero.\nWe just need to remove first and last character of primitive string.\n\nSo the intution is...\nIf you get c=0 do not take that character and the character next to it.\n\n# Approach\nIf you encounter c=0, it means previous substring was primitive. So the position at which you are currently, must be opening parenthesis. Make c= -1 and continue.\n```\n if (c == 0) {\n c--;\n continue;\n }\n```\n\nIf you got Opening parenthesis decreases the counter else for closing parenthesis increases the counter.\n```\n if (s[i] == \'(\') c--;\n else c++;\n```\n\nIf you got c=0, this is last character of primitive parenthesis. Therefore do not push it into ans str.\n```\n if (c == 0) continue;\n```\n\nElse push it into ans string.\n```\n str.push_back(s[i]);\n```\n\n# Code\n```\nclass Solution {\n public: string removeOuterParentheses(string s) {\n string str;\n int c = 0;\n for (int i = 0; i < s.size(); i++) {\n if (c == 0) {\n c--;\n continue;\n }\n if (s[i] == \'(\') c--;\n else c++;\n if (c == 0) continue;\n str.push_back(s[i]);\n }\n return str;\n }\n};\n```\n\n# Complexity\n```\n- Time complexity: O(n)\n```\n\n```\n- Space complexity: O(1)\n```\n\n if(helpful) Upvote++ ;\n \uD83D\uDC4D\uD83D\uDC4D\uD83D\uDC4D\uD83D\uDC4D\n\n ![image.png](https://assets.leetcode.com/users/images/56a4f661-44cb-4e7b-98be-49a7b8604658_1691592068.1438534.png)\n
6
0
['C++']
0
remove-outermost-parentheses
Python || 96.77% Faster || Explained || Without Stack || O(n) Solution
python-9677-faster-explained-without-sta-qfyt
\nclass Solution:\n def removeOuterParentheses(self, s: str) -> str:\n c,j,n=0,0,len(s)\n ans=[]\n for i in range(n):\n if s[
pulkit_uppal
NORMAL
2022-11-16T06:54:22.396264+00:00
2022-12-03T11:04:33.758468+00:00
1,647
false
```\nclass Solution:\n def removeOuterParentheses(self, s: str) -> str:\n c,j,n=0,0,len(s)\n ans=[]\n for i in range(n):\n if s[i]==\'(\':\n c+=1 #If there is opening paranthesis we increment the counter variable\n else:\n c-=1 #If there is closing paranthesis we decrement the counter variable\n#If counter variable is 0 it means that No. of opening paranthesis = No. of closing paranthesis and we get a set of valid parethesis \n\t\t\t\tif c==0:\n#Once we get a valid set of parenthesis we store it in the list where j is the starting index of the valid parenthesis set and i is the last index.\n#j+1 will remove the opening parenthesis and slicing the string till i(i.e., i-1) will store the valid set of parethesis in list after removing the outermost parenthis\n ans.append(s[j+1:i])\n j=i+1 #Changing the value of starting index for next valid set of parenthesis\n return \'\'.join(ans) #It will change the list into string\n```\n\n**Upvote if you like the solution or ask if there is any query**\n \n
6
0
['Python', 'Python3']
1
remove-outermost-parentheses
Simple, short and concise | C++
simple-short-and-concise-c-by-tusharbhar-905c
\nclass Solution {\npublic:\n string removeOuterParentheses(string str) {\n string ans = "";\n stack<char> s;\n \n for(char c : s
TusharBhart
NORMAL
2022-04-15T13:43:14.827114+00:00
2022-04-15T13:43:14.827140+00:00
327
false
```\nclass Solution {\npublic:\n string removeOuterParentheses(string str) {\n string ans = "";\n stack<char> s;\n \n for(char c : str){\n if(c == \'(\') s.push(c);\n if(s.size() > 1) ans += c;\n if(c == \')\') s.pop();\n }\n \n return ans;\n }\n};\n```
6
0
['Stack', 'C']
0
remove-outermost-parentheses
100% fastest solution | Explained every line | Efficient | Easy to understand | cpp | O(n)
100-fastest-solution-explained-every-lin-03gx
100% fastest solution | Explained every line | Efficient | Easy to understand | cpp | O(n)\n\nclass Solution {\npublic:\n string removeOuterParentheses(strin
divyanshnigam1612
NORMAL
2021-09-26T17:03:36.323918+00:00
2021-09-26T17:03:36.323947+00:00
795
false
100% fastest solution | Explained every line | Efficient | Easy to understand | cpp | O(n)\n```\nclass Solution {\npublic:\n string removeOuterParentheses(string s) \n {\n string ans;\n stack<char> st;\n\n for(auto x: s)\n {\n if(x==\'(\') // 1. ->add to stack 2. -> add to ans if not outermost\n {\n if(st.size()>0)\n ans.push_back(x);\n st.push(x);\n }\n else // 1. -> pop 2. -> add to ans if not empty\n {\n st.pop();\n if(!st.empty())\n ans.push_back(x);\n }\n }\n return ans;\n }\n};```
6
1
['Stack', 'C', 'C++']
0
remove-outermost-parentheses
Python simple solution with explanation
python-simple-solution-with-explanation-col7n
\nclass Solution:\n def removeOuterParentheses(self, S: str) -> str:\n result = \'\'\n depth = 0\n for index in range(0, len(S) - 1):\n
peatear-anthony
NORMAL
2021-01-17T04:14:17.169786+00:00
2021-01-17T04:24:16.382450+00:00
739
false
```\nclass Solution:\n def removeOuterParentheses(self, S: str) -> str:\n result = \'\'\n depth = 0\n for index in range(0, len(S) - 1):\n char = S[index]\n if depth != 0:\n result += char\n if char == "(" and S[index + 1] == "(":\n depth += 1\n elif char == ")" and S[index + 1] == ")":\n depth -= 1\n return result\n```\n\nThe **depth** variable represents how many levels into the primitive parentheses the current parenthesis is in. A depth value of zero represents a paraenteses belonging to a set primitive parentheses.\n\n## Logic\n- Subsequent opening parentheses will result in depth increasing by one\n- Subsequent closing parentheses will result in depth decreasing by one\n- A switch from closing to opening parenthesis \'(\' -> \')\' will not change the depth value\n- If the depth value is not 0 (i.e. not an outer parenthesis) add the current parenthesis to the result\n- The last parenthesis in the string S will always be a closing parenthesis [i.e. ")" ]\n\n\n### Example 1\n| Depth Value | 0 | 1 | 2 | 2 | 1 | 0 |\n|:-----------:|:-:|---|---|---|---|---|\n| char in S | ( | ( | ( | ) | ) | ) |\n\n\n### Example 2\n| Depth Value | 0 | 1 | 1 | 0 | 0 | 1 | 1 | 0 |\n|:-----------:|:-:|---|---|---|---|---|---|---|\n| char in S | ( | ( | ) | ) | ( | ( | ) | ) |\n
6
1
['Python', 'Python3']
0
remove-outermost-parentheses
Python solution beats 99%
python-solution-beats-99-by-soloz-cqdn
Traverse the string S from left to right. Time: O(N).\n\nUse the variable net to record the current net number of parenthese -- \'(\' contributes +1 and \')\' c
soloz
NORMAL
2019-07-19T03:41:44.679704+00:00
2019-07-19T03:41:44.679752+00:00
531
false
Traverse the string `S` from left to right. Time: O(N).\n\nUse the variable `net` to record the current net number of parenthese -- \'(\' contributes +1 and \')\' contributes -1. \n\nThe variable \'start\' is to store the starting index of the next primitive part in \'S\'.\n\nWhenever \'net\' becomes 0, one concludes that from the start position to the current position we have a primitive part. Update `res` by adding this primitive part without the starting \'(\' and the ending \')\'. Also, reset `start`.\n\n```\nclass Solution:\n def removeOuterParentheses(self, S: str) -> str:\n net, res, start = 0 , \'\', 0\n for i in range(len(S)):\n \n if S[i] == \'(\':\n net += 1\n else:\n net -= 1\n \n if net == 0:\n res += S[start+1:i]\n start = i + 1\n return res\n```
6
0
[]
0
remove-outermost-parentheses
simple and easy C++ solution 😍❤️‍🔥
simple-and-easy-c-solution-by-shishirrsi-kwmn
\n# if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n###### Let\'s Connect on LinkedIn: www.linkedin.com/in/shishirrsiam\n###### Let\'s Connect on Facebook
shishirRsiam
NORMAL
2024-08-21T03:35:36.834773+00:00
2024-08-21T03:35:36.834803+00:00
867
false
\n# if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n###### Let\'s Connect on LinkedIn: www.linkedin.com/in/shishirrsiam\n###### Let\'s Connect on Facebook: www.fb.com/shishirrsiam\n\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n string removeOuterParentheses(string s) \n {\n string ans;\n int cnt = 0;\n for(char ch:s)\n {\n if(ch == \'(\') \n {\n if(cnt) ans += ch;\n cnt++;\n }\n else \n {\n cnt--;\n if(cnt) ans += ch;\n }\n }\n return ans;\n }\n};\n```
5
0
['String', 'Stack', 'C++']
4
remove-outermost-parentheses
✅ 2 POINTER APPROACH || Beats 100%✅ || C++ || Without Using Stack || BEGINNER FRIENDLY
2-pointer-approach-beats-100-c-without-u-o78k
Intuition\nGiven the problem of removing the outermost parentheses from every primitive valid parentheses string in a given valid parentheses string s, the main
V15H4L
NORMAL
2024-06-10T15:46:25.279248+00:00
2024-06-10T15:46:25.279278+00:00
451
false
# Intuition\nGiven the problem of removing the outermost parentheses from every primitive valid parentheses string in a given valid parentheses string `s`, the main idea is to identify these primitive segments and remove their outermost parentheses. A two-pointer approach can be effectively used to identify these segments.\n\n# Approach\n1. Use two pointers, `left` and `right`, to traverse the string `s`.\n2. Maintain a counter `cnt` to keep track of the balance of parentheses.\n3. Increment `right` and update `cnt` based on whether the current character is `(` or `)`.\n4. When `cnt` reaches zero, it means we have a complete primitive valid parentheses string from `left` to `right`.\n5. Extract the inner content of this primitive string by taking the substring from `left + 1` to `right - 1` and append it to the result.\n6. Reset `left` to `right + 1` and continue until the end of the string is reached.\n\n# Complexity\n- Time complexity:\n$$O(n)$$, where \\(n\\) is the length of the string. Each character is processed once.\n\n- Space complexity:\n$$O(n)$$, where \\(n\\) is the length of the string. The resulting string `ans` is at most the size of the input string `s`.\n\n# Code\n```cpp\nclass Solution {\npublic:\n string removeOuterParentheses(string s) {\n int left = 0, right = 0;\n string ans = "";\n int n = s.length(), cnt = 0;\n \n while (right < n) {\n if (s[right] == \'(\') {\n cnt++;\n } else {\n cnt--;\n }\n \n if (cnt == 0) {\n if (left <= right) {\n ans += s.substr(left + 1, right - left - 1);\n right++;\n left = right;\n continue;\n }\n }\n right++;\n }\n \n return ans;\n }\n};\n```\n\n![image.png](https://assets.leetcode.com/users/images/9b38dbc2-f1a5-4b57-85b9-6728d292d5d9_1718034205.5414898.png)\n\n\nPLEASE UPVOTE IT IF YOU LIKED IT, IT REALLY MOTIVATES ME A LOT:)
5
0
['Two Pointers', 'String', 'C++']
0
remove-outermost-parentheses
easy way 🔥|| without stack
easy-way-without-stack-by-tanmay_jaiswal-eqmd
\nclass Solution {\npublic:\n string removeOuterParentheses(string s) {\n int cnt = 0;\n string res;\n\n for (auto c: s) {\n
tanmay_jaiswal_
NORMAL
2023-07-11T21:51:51.041348+00:00
2023-07-11T21:51:51.041371+00:00
1,174
false
```\nclass Solution {\npublic:\n string removeOuterParentheses(string s) {\n int cnt = 0;\n string res;\n\n for (auto c: s) {\n if (cnt == 0 && c == \'(\') cnt--;\n else if (cnt == -1 && c == \')\') cnt++;\n else {\n res.push_back(c);\n if (c == \'(\') cnt--;\n else cnt++;\n }\n }\n\n return res;\n }\n};\n```\n---\n**compact code**\n\n---\n```\nclass Solution {\npublic:\n string removeOuterParentheses(string s) {\n int cnt = 0;\n string res;\n\n for (auto c: s) {\n if (c == \'(\' && cnt++ > 0 ) res.push_back(c);\n if (c == \')\' && cnt-- > 1 ) res.push_back(c);\n }\n\n return res;\n }\n};\n```
5
0
['C++']
0
remove-outermost-parentheses
Best O(N) Solution
best-on-solution-by-kumar21ayush03-f038
\n\n# Approach\nBest Approach\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n\nclass Solution {\npublic:\n string removeOu
kumar21ayush03
NORMAL
2023-01-28T14:33:52.555811+00:00
2023-01-28T14:33:52.555861+00:00
535
false
\n\n# Approach\nBest Approach\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nclass Solution {\npublic:\n string removeOuterParentheses(string s) {\n int count = 0;\n string ans = "";\n for (int i = 0; i < s.size(); i++) {\n if (s[i] == \'(\') {\n if (count > 0)\n ans += s[i]; \n count++;\n }\n if (s[i] == \')\') {\n if (count > 1)\n ans += s[i];\n count--;\n } \n }\n return ans;\n }\n};\n```
5
0
['C++']
0
remove-outermost-parentheses
simple cpp solution using stack
simple-cpp-solution-using-stack-by-prith-k8uq
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
prithviraj26
NORMAL
2023-01-24T16:50:43.248159+00:00
2023-01-24T16:50:43.248215+00:00
873
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n string removeOuterParentheses(string s) \n {\n string ans="";\n stack<char>st;\n for(int i=0;i<s.length();i++)\n {\n if(st.empty()&&s[i]==\'(\')\n {\n st.push(\'(\');\n }\n else\n {\n if(st.size()>0 &&s[i]==\'(\')\n {\n st.push(\'(\');\n ans+=\'(\';\n }\n else if(st.size()>1 && s[i]==\')\')\n {\n st.pop();\n ans+=\')\';\n }\n else\n {\n st.pop();\n }\n }\n }\n return ans;\n \n }\n};\n```
5
0
['String', 'Stack', 'C++']
0
remove-outermost-parentheses
Java | without using stack | simple one
java-without-using-stack-simple-one-by-v-u7vp
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
Venkat089
NORMAL
2023-01-17T09:05:53.234559+00:00
2023-01-17T09:05:53.234700+00:00
1,782
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public String removeOuterParentheses(String s) {\n String res="";\n int k=0;\n int op=0;\n for(int i=0;i<s.length();i++)\n {\n if(s.charAt(i)==\'(\')op++;\n else op--;\n if(op==0){\n res+=help(s.substring(k,i+1));\n k=i+1;\n }\n }\n return res;\n }\n\n public static String help(String str)\n {\n return str.substring(1,str.length()-1);\n }\n}\n\n/*\n s = "( ()() ) ( () )"\n int k=0;\n open=0;close=0;\n ( op=1 ( op=1\n (op=2 ( op=2\n )op=1 ) op=1\n (op=2 ) op=0\n )op=1\n)op=0\nwhen op becomes 0 (op=0) , we gonna found one decompose string and removing it\'s outer most parenthese\n*/\n\n```
5
0
['Java']
0
remove-outermost-parentheses
[Java] ✅Faster Solution 99.85% Big O(N) || Without Stack
java-faster-solution-9985-big-on-without-bvma
\n\n# Code\n\nclass Solution {\n public String removeOuterParentheses(String s) {\n int count = 0;\n StringBuilder str = new StringBuilder();\n
deleted_user
NORMAL
2022-11-21T03:57:10.143050+00:00
2022-11-21T03:57:59.332065+00:00
1,060
false
\n\n# Code\n```\nclass Solution {\n public String removeOuterParentheses(String s) {\n int count = 0;\n StringBuilder str = new StringBuilder();\n\n for(int i = 0; i<s.length(); i++){\n if( s.charAt(i) == \'(\'){\n count++;\n if(count>=2) str.append(\'(\');\n }else {\n if(count>=2) str.append(\')\');\n count--;\n }\n }\n\n return str.toString();\n }\n}\n```
5
0
['Java']
0
remove-outermost-parentheses
C++ Easy understandable solution using stack
c-easy-understandable-solution-using-sta-hr6f
\nstring removeOuterParentheses(string s) {\n stack<char>s1;\n string ans="";\n for(int i=0;i<s.size();i++)\n {\n if(s[i]
Kalim123
NORMAL
2022-03-18T06:08:24.450061+00:00
2022-03-18T06:08:24.450087+00:00
556
false
```\nstring removeOuterParentheses(string s) {\n stack<char>s1;\n string ans="";\n for(int i=0;i<s.size();i++)\n {\n if(s[i]==\'(\')\n {\n if(s1.size()>0)\n ans+=\'(\';\n s1.push(\'(\');\n }else\n {\n if(s1.size()>1)\n ans+=\')\';\n s1.pop();\n }\n \n }\n return ans;\n }\n```
5
0
['Stack', 'C', 'C++']
0
remove-outermost-parentheses
Javascript Stack oriented solution
javascript-stack-oriented-solution-by-kr-bz4s
var removeOuterParentheses = function(S) {\n\n let stack = [];\n let result = \'\';\n for (const s of S) {\n if( s === \'(\') {\n if (s
kraiymbek
NORMAL
2021-06-30T14:46:35.152731+00:00
2021-06-30T14:46:35.152774+00:00
349
false
var removeOuterParentheses = function(S) {\n\n let stack = [];\n let result = \'\';\n for (const s of S) {\n if( s === \'(\') {\n if (stack.length) {\n result+=s;\n }\n stack.push(s);\n } else {\n stack.pop();\n if (stack.length) {\n result+=s;\n }\n }\n }\n\n return result;\n};
5
0
['JavaScript']
1
remove-outermost-parentheses
python simple solution speed 98.46% and memory 99.39%
python-simple-solution-speed-9846-and-me-brfu
\nclass Solution:\n def removeOuterParentheses(self, S: str) -> str:\n ans = []\n l = []\n count = 0\n for i in S:\n l
baranee18
NORMAL
2021-05-15T08:45:48.352406+00:00
2021-06-06T08:46:13.180509+00:00
389
false
```\nclass Solution:\n def removeOuterParentheses(self, S: str) -> str:\n ans = []\n l = []\n count = 0\n for i in S:\n l.append(i)\n if i == \'(\':\n count+= 1\n else:\n count -= 1\n if count == 0:\n ans.extend(l[1:-1])\n l = []\n return "".join(ans)\n\t\t\n\t# Kindly upvote if you find it useful !!\n```
5
0
['Python']
0
remove-outermost-parentheses
C++ | Faster than 100% | Easy
c-faster-than-100-easy-by-pranjalb-30vq
A simple iterative program that iterates on the string.\nWe use a variable flag to cound the number of left parenthesis. Since we just have to remove one parent
pranjalb
NORMAL
2020-12-01T06:29:30.785592+00:00
2020-12-01T06:29:30.785643+00:00
506
false
A simple iterative program that iterates on the string.\nWe use a variable flag to cound the number of left parenthesis. Since we just have to remove one parenthesis only, we check if the flag value is greater than 1, and then add characters to the resultant string.\n\n```\nConsider the following test case\n\n\tS = "(()())(())"\n\t\t\n\t\t\t1. S[i] = "(" , flag = 1, result = "";\n\t\t\t2. S[i] = "(" , flag = 2, result = "(";\n\t\t\t3. S[i] = ")" , flag = 1, result = "()";\n\t\t\t4. S[i] = "(" , flag = 2, result = "()(";\n\t\t\t5. S[i] = ")" , flag = 1, result = "()()";\n\t\t\t6. S[i] = ")" , flag = 0, result = "()()";\n\t\t\t7. S[i] = "(" , flag = 1, result = "()()";\n\t\t\t8. S[i] = "(" , flag = 2, result = "()()(";\n\t\t\t9. S[i] = ")" , flag = 1, result = "()()()";\n\t\t\t10. S[i] = ")" , flag = 0, result = "()()()";\n\t\t\t\n\t\t\tresult = "()()()";\n\t\t\treturn result;\n```\n\n```\n\nclass Solution {\npublic:\n string removeOuterParentheses(string S) {\n int flag = 0,l = int(S.length());\n string result;\n for(int i = 0;i < l;i++){\n if(S[i] == \'(\'){\n flag += 1;\n result += flag > 1 ? "(" : "";\n } else {\n flag -= 1;\n result += flag > 0 ? ")" : "";\n }\n }\n return result;\n }\n};\n\n```\n\n![image](https://assets.leetcode.com/users/images/66145b21-665b-4402-ae74-2c6565dceefe_1606804144.1577873.png)\n
5
0
['C', 'C++']
0
remove-outermost-parentheses
Simple Java Solution
simple-java-solution-by-kumarpallav-s26q
\nclass Solution {\n public String removeOuterParentheses(String S) {\n \n \tchar [] chars=S.toCharArray();\n \tStringBuilder sb=new StringBuil
kumarpallav
NORMAL
2020-08-10T11:25:31.520694+00:00
2020-08-10T11:25:31.520739+00:00
985
false
```\nclass Solution {\n public String removeOuterParentheses(String S) {\n \n \tchar [] chars=S.toCharArray();\n \tStringBuilder sb=new StringBuilder();\n \tStack<Character> st= new Stack<>();\n \tint startindex=0;\n \tfor ( int i=0;i<chars.length;i++ ) {\n \t\tchar c= chars[i];\n \t\tif(c==\'(\') {\n \t\t\tst.push(\'(\');\n \t\t}else if(c==\')\') {\n \t\t\tst.pop();\n \t\t}\n \t\tif(st.isEmpty()) {\n \t\t\tsb.append(S.substring((startindex+1),i));\n \t\t\tstartindex=i+1;\n \t\t}\n \t\t\n \t}\n \t\n return sb.toString();\n \n }\n}\n```
5
0
['Java']
2
remove-outermost-parentheses
Simple String operation....No STACKS USED....Easy to Understand
simple-string-operationno-stacks-usedeas-3pkf
\nclass Solution {\n public String removeOuterParentheses(String S) {\n String k="",s="";int c=0,d=0;// c-> to count no. of \'(\' and d->no. of \')\'
jayantbabu2868
NORMAL
2020-05-25T09:41:22.497087+00:00
2020-05-25T09:41:22.497140+00:00
435
false
```\nclass Solution {\n public String removeOuterParentheses(String S) {\n String k="",s="";int c=0,d=0;// c-> to count no. of \'(\' and d->no. of \')\' \n for(int i=0;i<S.length();i++)\n {\n if(S.charAt(i)==\'(\'){\n s=s+\'(\';\n c++;\n }\n else if(S.charAt(i)==\')\')\n {\n s=s+\')\';\n d++;\n }\n if(c==d)// when c==d means one complete bracket series ended....eg: (()()) c==d for this.... \n {\n k=k+s.substring(1,s.length()-1);// select the string execpt first and last portion 1 -> s.length()-1,which gives ()()\n s="";//this for next bracket series\n c=d=0;//for next bracket series....\n }\n }\n return k;\n }\n}\n```
5
0
['String', 'Java']
1
remove-outermost-parentheses
C solution
c-solution-by-zhaoyaqiong-33zj
\nchar * removeOuterParentheses(char * S){\n char *str = malloc(sizeof(char) * strlen(S));\n int flag = 0,p = 0;\n for (int i = 0;i < strlen(S); i++) {
zhaoyaqiong
NORMAL
2020-01-20T09:00:32.215745+00:00
2020-01-20T09:00:32.215792+00:00
490
false
```\nchar * removeOuterParentheses(char * S){\n char *str = malloc(sizeof(char) * strlen(S));\n int flag = 0,p = 0;\n for (int i = 0;i < strlen(S); i++) {\n if (S[i]==\'(\') {\n flag++;\n if (flag != 1) {\n str[p++] = S[i];\n }\n }else{\n flag--;\n if(flag!=0){\n str[p++] = S[i];\n }\n }\n }\n str[p] = 0;\n return str;\n}\n```
5
0
[]
0
remove-outermost-parentheses
C#
c-by-mhorskaya-smkh
\npublic string RemoveOuterParentheses(string S) {\n\tvar str = new StringBuilder();\n\tvar i = 0;\n\n\tforeach (var c in S.ToCharArray()) {\n\t\ti += c == \'(\
mhorskaya
NORMAL
2020-01-02T08:48:25.184738+00:00
2020-01-02T08:48:25.184790+00:00
360
false
```\npublic string RemoveOuterParentheses(string S) {\n\tvar str = new StringBuilder();\n\tvar i = 0;\n\n\tforeach (var c in S.ToCharArray()) {\n\t\ti += c == \'(\' ? 1 : -1;\n\n\t\tif (c == \'(\' && i > 1 || c == \')\' && i > 0)\n\t\t\tstr.Append(c);\n\t}\n\n\treturn str.ToString();\n}\n```
5
1
[]
1
remove-outermost-parentheses
javascript
javascript-by-suxiaohui1996-8l7b
\nvar removeOuterParentheses = function(S) {\n let res = \'\',\n leftNum = 0;\n for(let i = 0; i < S.length; ++i) {\n if(S.charAt(i) == \'(\
suxiaohui1996
NORMAL
2019-04-08T02:08:24.646844+00:00
2019-04-08T02:08:24.646880+00:00
827
false
```\nvar removeOuterParentheses = function(S) {\n let res = \'\',\n leftNum = 0;\n for(let i = 0; i < S.length; ++i) {\n if(S.charAt(i) == \'(\') {\n leftNum ++;\n if(leftNum == 2) {\n while(leftNum > 0) {\n res += S.charAt(i);\n S.charAt(++i) == \'(\' ? leftNum ++ : leftNum --;\n \n }\n }\n } else\n leftNum --;\n }\n return res;\n};\n```
5
0
[]
0
remove-outermost-parentheses
Python // C++ // Haskell Solutions
python-c-haskell-solutions-by-code_repor-pw9c
Video Explanation: https://www.youtube.com/watch?v=ekdNNn3vOqQ\n\n1. Group by parentheses substring when LEFT = RIGHT\n2. Then just shave off the first and last
code_report
NORMAL
2019-04-07T04:01:38.032094+00:00
2019-04-07T04:01:38.032136+00:00
674
false
**Video Explanation:** https://www.youtube.com/watch?v=ekdNNn3vOqQ\n\n1. Group by parentheses substring when LEFT = RIGHT\n2. Then just shave off the first and last parentheses of each group and rejoin\n\n**Python Solution 1:**\n```\ndef group(S):\n\tt, a, l = 0, 0, []\n for i in range(len(S)):\n t = t + 1 if S[i] == \'(\' else t - 1\n if t == 0:\n l.append(S[a:i+1])\n a = i + 1\n return l\n\nclass Solution:\n def removeOuterParentheses(self, S: str) -> str:\n return \'\'.join(sub[1:-1] for sub in group(S))\n```\n**Python Solution 2 (Functional Programming):**\n```\ndef group(S: str) -> str:\n a = [1 if i == \'(\' else -1 for i in S] \n b = [0] + [i+1 for i, j in enumerate(itertools.accumulate(a)) if j == 0]\n return [S[i:j] for i, j in zip(b[:-1], b[1:])]\n\nclass Solution:\n def removeOuterParentheses(self, S: str) -> str:\n return \'\'.join(sub[1:-1] for sub in group(S))\n```\n**Haskell:**\n```\nremoveOuterParentheses s = concat $ map (tail . init) primitives\n where primitives = map (map fst) $ init $ segmentAfter ((==0) . snd) (zip s (parenCount s))\n parenCount = scanl1 (+) . map (\\e -> if e == \'(\' then 1 else -1)\n```\n**C++:**\n```\nstring removeOuterParentheses(string S) {\n vector<int> a(S.size()), b(S.size());\n transform(S.begin(), S.end(), a.begin(), [](auto c) { return c == \'(\' ? 1 : -1; });\n partial_sum(a.begin(), a.end(), b.begin());\n return accumulate(b.begin(), b.end(), string(),\n [&S, t = string(), i = 0](auto s, auto e) mutable {\n e == 0 ? s += t.substr(1, t.size() - 1), t = "" : t += S[i]; ++i;\n return s;\n });\n}\n```\n
5
0
['C', 'Python']
0
remove-outermost-parentheses
100% Beat, C++ Solution using stack, Time and space complexity -O(n)
100-beat-c-solution-using-stack-time-and-q025
IntuitionThe problem requires us to remove the outermost parentheses of every valid primitive string in the input. A primitive string is a valid, non-empty pare
cbirla14
NORMAL
2025-03-10T14:28:30.235227+00:00
2025-03-10T14:28:30.235227+00:00
415
false
# Intuition The problem requires us to remove the outermost parentheses of every valid primitive string in the input. A primitive string is a valid, non-empty parenthesis substring that cannot be split further. The key observation is that the first and last parentheses of each valid primitive group should be removed. We can use a stack to track balance and determine which parentheses belong to the outermost layer. # Approach 1. Initialize a stack to keep track of open parentheses. 2. Iterate through the string character by character: 1. If the stack is empty, it means we are at the start of a new primitive group, so we do not add the first '(' to the result. 2. Push '(' onto the stack when encountered. 3. When encountering ')', pop an element from the stack: 1. If the stack is still not empty after popping, append ')' to the result, since it is not an outer parenthesis. 3. The stack ensures that we only add characters that are not the first or last parentheses of a primitive group. 4. Return the final modified string. # Complexity - Time complexity: We traverse the string once (O(n)) and perform constant-time operations inside the loop (O(1)). Overall: O(n). - Space Complexity: The stack holds at most O(n) elements in the worst case. However, since we only use it to track valid parentheses and do not store extra large data, this can be considered O(1) auxiliary space (excluding input and output). The answer string takes O(n) space in the worst case. Overall: O(n) (for output storage). # Code ```cpp [] class Solution { public: string removeOuterParentheses(string s) { stack<char>stack; string ans; if(s.empty())return ""; int n=s.length(); for(int i=0;i<n;i++){ if(stack.empty()) { stack.push(s[i]); continue; } if(s[i]=='('){ stack.push('('); } if(s[i]==')'){ stack.pop(); } if(!stack.empty()) { ans+=s[i]; } } return ans; } }; ```
4
0
['String', 'Stack', 'C++']
0
remove-outermost-parentheses
Removing Outer Layers of Parentheses in Linear Time || 4ms Runtime
removing-outer-layers-of-parentheses-in-564fk
Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem is about removing the outermost parentheses from a valid string of parenthe
somyaParikh
NORMAL
2024-08-24T17:05:48.200276+00:00
2024-08-24T17:05:48.200331+00:00
1,255
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem is about removing the outermost parentheses from a valid string of parentheses. The idea is that for each balanced section of the string (or primitive), you want to remove the first opening parenthesis ( and the last closing parenthesis ).\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Tracking the Balance: We maintain a counter count to keep track of the balance between the opening ( and closing ) parentheses. This helps us identify when we are inside a balanced group of parentheses.\n\n2. Iterate Through the String: We iterate through each character in the string s:\n\n- If the character is an opening parenthesis (:\n - If count is not zero, it means we are inside a balanced group (not at the outermost level), so we add this ( to our answer string ans.\n - Increment the count since we encountered an opening parenthesis.\n- If the character is a closing parenthesis ):\n - Decrement the count first. If the count is still greater than zero after decrementing, it means we are inside a balanced group, so we add this ) to ans.\n\n3. Building the Result: The result string ans accumulates all the characters that are not part of the outermost parentheses.\n\n4. Return the Result: After iterating through the entire string, we return the string ans which contains the input string s with the outermost parentheses removed.\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity is O(n), where n is the length of the string s. We iterate through the string once, making this approach linear in time.\n\n- Space complexity: O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nSpace Complexity: The space complexity is O(n), as we are creating a new string ans to store the result. In the worst case, this string could be nearly as long as the input string s.\n\n# Code\n```cpp []\nclass Solution {\npublic:\n string removeOuterParentheses(string s) {\n int count = 0;\n string ans = "";\n int i = 0, n = s.size();\n\n while(i < n) {\n if(s[i] == \'(\') {\n if(count != 0) {\n ans += s[i];\n }\n count++; \n } else if (s[i] == \')\') {\n if(count > 1) {\n ans += s[i];\n }\n count--; \n }\n\n i++;\n }\n return ans;\n }\n};\n```\n```java []\nclass Solution {\n public String removeOuterParentheses(String s) {\n int count = 0;\n StringBuilder ans = new StringBuilder();\n\n for (char c : s.toCharArray()) {\n if (c == \'(\') {\n if (count != 0) {\n ans.append(c);\n }\n count++;\n } else {\n if (count > 1) {\n ans.append(c);\n }\n count--;\n }\n }\n\n return ans.toString();\n }\n}\n\n```\n```javascript []\nvar removeOuterParentheses = function(s) {\n let count = 0;\n let ans = \'\';\n\n for (let c of s) {\n if (c === \'(\') {\n if (count !== 0) {\n ans += c;\n }\n count++;\n } else {\n if (count > 1) {\n ans += c;\n }\n count--;\n }\n }\n\n return ans;\n};\n\n```\n```python []\nclass Solution:\n def removeOuterParentheses(self, s: str) -> str:\n count = 0\n ans = []\n\n for c in s:\n if c == \'(\':\n if count != 0:\n ans.append(c)\n count += 1\n else:\n if count > 1:\n ans.append(c)\n count -= 1\n\n return \'\'.join(ans)\n\n```\n\n
4
0
['String', 'Python', 'C++', 'Java', 'JavaScript']
0
remove-outermost-parentheses
SIMPLE STACK COMMENTED C++ SOLUTION
simple-stack-commented-c-solution-by-jef-i82c
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
Jeffrin2005
NORMAL
2024-07-24T12:58:00.120363+00:00
2024-07-24T12:58:00.120399+00:00
843
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:o(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:o(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n\nclass Solution {\npublic:\n string removeOuterParentheses(string s) {\n string result;\n stack<char> stack;\n int start = 0; // Start index of a primitive block\n int n = s.size();\n for(int i = 0; i <n; i++){\n if(s[i] == \'(\') {\n stack.push(\'(\');\n }else{\n stack.pop();\n }\n // When the stack is empty, we found a complete primitive block\n if(stack.empty()){\n // Append all except the outermost parentheses\n result += s.substr(start + 1, i - start - 1);\n start = i + 1; // Update the start for the next primitive block\n }\n }\n\n return result;\n }\n};\n```
4
0
['C++']
0
remove-outermost-parentheses
Easy Solution 🧩 A Step-by-Step Guide in Java, Python, and C++ 📚
easy-solution-a-step-by-step-guide-in-ja-y7yh
Intuition\nTo solve the problem of removing outermost parentheses, the main idea is to track the balance of parentheses using a counter. When traversing the str
prashu1818
NORMAL
2024-07-08T19:25:44.534848+00:00
2024-07-08T19:25:44.534881+00:00
882
false
# Intuition\nTo solve the problem of removing outermost parentheses, the main idea is to track the balance of parentheses using a counter. When traversing the string, we use the counter to determine if the current parenthesis is part of the outermost pair. If it is not, we add it to the result string.\n\n# Approach\n1. Initialize:\n\n- Use a StringBuilder (or equivalent) to build the result string efficiently.\n- Use a counter to track the depth of parentheses.\n2. Loop Through the String:\n\n- For each character in the input string:\n- If it\'s a closing parenthesis ), decrease the counter first.\n- If the counter is not zero, append the character to the result.\n- If it\'s an opening parenthesis (, increase the counter after the check.\n3. Return the Result:\n\n- Convert the StringBuilder to a string and return it.\n\n# Complexity\n- Time complexity: The time complexity is O(n), where \uD835\uDC5B is the length of the input string s, since we process each character exactly once.\n\n- Space complexity:\nThe space complexity is O(n) due to the space used by the StringBuilder to store the result.\n\n# Code\n\n```java []\nclass Solution {\n public String removeOuterParentheses(String s) {\n StringBuilder ans = new StringBuilder();\n int count = 0;\n\n for(int i=0; i<s.length(); i++) {\n char c = s.charAt(i);\n if(c == \')\') count--;\n if(count !=0) ans.append(c);\n if(c == \'(\') count++;\n }\n return ans.toString();\n }\n}\n```\n```python []\nclass Solution:\n def removeOuterParentheses(self, s: str) -> str:\n ans = []\n count = 0\n\n for char in s:\n if char == \')\':\n count -= 1\n if count != 0:\n ans.append(char)\n if char == \'(\':\n count += 1\n\n return \'\'.join(ans)\n```\n```C++ []\nclass Solution {\npublic:\n std::string removeOuterParentheses(std::string s) {\n std::string ans;\n int count = 0;\n\n for(char c : s) {\n if(c == \')\') count--;\n if(count != 0) ans += c;\n if(c == \'(\') count++;\n }\n return ans;\n }\n};\n```\n```
4
0
['String', 'C++', 'Java', 'Python3']
2
remove-outermost-parentheses
Explained || Optimized || Interview Question || C++
explained-optimized-interview-question-c-3ygz
Intuition\n Describe your first thoughts on how to solve this problem. \nitna to samjh aa jaata hai saab, 350 ques karne k baad\n\n# Approach\n Describe your ap
satwikjain104
NORMAL
2023-07-17T14:38:47.652982+00:00
2023-07-17T14:38:47.653005+00:00
547
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nitna to samjh aa jaata hai saab, 350 ques karne k baad\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\njust use the stack \n\n# Complexity\n- Time complexity:\nO(n), n is size of given string\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n\n# Code\n```\nclass Solution {\npublic:\n//see- https://www.youtube.com/watch?v=MLfAFCkzChU\n/* algo:\n 1. check stack empty ? if true then put the 1st char and this will be not ans as it\'s outermost.\n\n 2. add another cha, check stack is empty or not, if not then it means this char should be in our ans string add it their and then place it inside stack.\n\n 3. add another char if it\'s a closing bracket then remove it\'s opening bracket from stack and check if stack gets empty after this or not, if yes then it was outermost don\'t add in ans, if not empty the this can be added to ans string.\n*/\n\n string removeOuterParentheses(string s) {\n stack<char> st;\n if(s=="" || s=="()") return "";\n string ans="";\n int n=s.size();\n int i=0;\n while(i<n)\n {\n if(st.empty())\n {\n st.push(s[i]);\n \n }\n else\n {\n if(s[i]==\'(\')\n {\n ans+=s[i];\n st.push(s[i]);\n \n }\n else\n {\n st.pop();\n if(!st.empty()) ans+=s[i];\n }\n }\n i++;\n }\n return ans;\n// PLEASE UPVOTE THANK YOU\n }\n};\n```
4
0
['C++']
1
remove-outermost-parentheses
✅ Aesthetic TypeScript
aesthetic-typescript-by-mlajkim-j3vh
Code\nts\nfunction removeOuterParentheses(s: string): string {\n let level = 0\n let built: string = ""\n for (const c of s) {\n if (c === "(" &
mlajkim
NORMAL
2023-07-09T19:55:22.098705+00:00
2023-07-09T19:55:22.098728+00:00
109
false
# Code\n```ts\nfunction removeOuterParentheses(s: string): string {\n let level = 0\n let built: string = ""\n for (const c of s) {\n if (c === "(" && level++ === 0) continue\n if (c === ")" && level-- === 1) continue\n built += c\n }\n return built\n};\n```\n\n# Thank you\nUpvote if you like \u2B06\uFE0F\nIf you have any questions, please let me know in the comment section.
4
0
['TypeScript']
0
remove-outermost-parentheses
C++ EASY AND CLEAN CODE
c-easy-and-clean-code-by-arpiii_7474-9ksq
Code\n\nclass Solution {\npublic:\n string removeOuterParentheses(string s) {\n stack<char> st;\n string res="";\n for(int i=0;i<s.size(
arpiii_7474
NORMAL
2023-06-28T04:18:46.990281+00:00
2023-06-28T04:18:46.990312+00:00
1,471
false
# Code\n```\nclass Solution {\npublic:\n string removeOuterParentheses(string s) {\n stack<char> st;\n string res="";\n for(int i=0;i<s.size();i++){\n if(s[i]==\'(\' && st.empty()){\n st.push(s[i]);\n }\n else if(s[i]==\'(\'){\n st.push(s[i]);\n res+=s[i];\n }\n else{\n st.pop();\n if(st.size()){\n res+=s[i];\n }\n }\n }\n return res;\n }\n};\n```
4
0
['C++']
2
remove-outermost-parentheses
[ Python ] | Simple & Clean Solution
python-simple-clean-solution-by-yash_vis-vekh
Code\n\nclass Solution:\n def removeOuterParentheses(self, s: str) -> str:\n ans, cnt = [], 0\n for ch in s:\n if ch == \'(\' and cn
yash_visavadia
NORMAL
2023-05-02T16:36:02.038554+00:00
2023-05-02T16:36:02.038601+00:00
1,553
false
# Code\n```\nclass Solution:\n def removeOuterParentheses(self, s: str) -> str:\n ans, cnt = [], 0\n for ch in s:\n if ch == \'(\' and cnt > 0: ans.append(ch)\n if ch == \')\' and cnt > 1: ans.append(ch)\n cnt += 1 if ch == \'(\' else -1\n return "".join(ans)\n```
4
1
['Python3']
0
remove-outermost-parentheses
Easily Understandable JAVA Stack & Without Stack sol.
easily-understandable-java-stack-without-8nn7
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
harsh_tiwari_
NORMAL
2023-04-22T16:42:18.325789+00:00
2023-04-22T16:42:18.325820+00:00
1,263
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public String removeOuterParentheses(String s) {\n StringBuilder sb = new StringBuilder();\n\n// STACK SOLUTION\n\n // Stack<Character> st = new Stack<>();\n // for(int i=0;i<s.length();i++){\n // char ch = s.charAt(i);\n // if(ch == \'(\'){\n // if(!st.isEmpty()){\n // sb.append(ch);\n // }\n // st.push(ch); \n // }else{\n // st.pop();\n // if(!st.isEmpty()){\n // sb.append(ch);\n // }\n // }\n // }\n // return sb.toString();\n \n int con=0;\n for(char c:s.toCharArray()){\n if(c==\'(\' && con++>0 )sb.append(c);\n if(c==\')\' && con-->1 )sb.append(c);\n }\n return sb.toString();\n }\n}\n/* \n-->Solve without using stack:\nKeep a counter c = 0\nIncrement when ( found and decrement when ) found\nif c = 1 means ( is outer most, don\'t add it to answer\nif c = 0 means ) is outer most, don\'t add it to answer\nelse keep adding parenthesis to answer\n*/\n```
4
0
['Java']
0
remove-outermost-parentheses
Go(golang) solution
gogolang-solution-by-azizjon003-2utj
\n# Complexity\n- Time complexity:\n Add your time complexity here, e.g. O(n) \n\n- Space complexity:\n Add your space complexity here, e.g. O(n) \n\n# Code\n\n
Azizjon003
NORMAL
2023-04-10T18:12:11.193076+00:00
2023-04-10T18:12:11.193116+00:00
554
false
\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nfunc removeOuterParentheses(s string) string {\n var result string\n var index int\n\n for _, x := range s {\n switch x {\n case \'(\':\n if index > 0 {\n result += string(x)\n }\n index++\n case \')\':\n index--\n if index > 0 {\n result += string(x)\n }\n }\n }\n\n return result\n}\n\n```
4
0
['Array', 'Go']
0
remove-outermost-parentheses
O(N) solution using stack|beats 100% | C++
on-solution-using-stackbeats-100-c-by-kg-jyn3
Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(N)\n\n# Code\n\nclass Solution {\npublic:\n string removeOuterParentheses(string s) {\n\n
kgharat008769321
NORMAL
2023-03-08T14:13:27.300834+00:00
2023-03-08T14:13:27.300866+00:00
879
false
# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(N)\n\n# Code\n```\nclass Solution {\npublic:\n string removeOuterParentheses(string s) {\n\n stack<char> st;\n string ans="";\n\n for(auto c: s){\n\n if(!st.empty()) ans+=c;\n if(c==\'(\') st.push(c);\n else {\n st.pop();\n if(st.empty()) ans.pop_back();\n }\n \n }\n\n return ans;\n \n }\n};\n```
4
0
['C++']
0
remove-outermost-parentheses
clean, readable code [C++]
clean-readable-code-c-by-vishshukla-l4m6
Intuition\nEasy one-liner in C++\n\n# Approach\nYou don\'t need Python, when you know C++ like me\n\n# Complexity\n- Time complexity: O(-1)\n\n- Space complexit
vishshukla
NORMAL
2023-02-10T21:44:42.054142+00:00
2023-02-10T21:45:38.527281+00:00
1,011
false
# Intuition\nEasy one-liner in C++\n\n# Approach\nYou don\'t need Python, when you know C++ like me\n\n# Complexity\n- Time complexity: O(-1)\n\n- Space complexity: O(inf)\n\n# Code\n```\nclass Solution {public:string removeOuterParentheses(string s) {string output;int count = 0;for (auto c : s) {if (c == \')\') count--;if (count != 0) output += c;if (c == \'(\') count++;}return output;}};\n```
4
0
['C++']
6
remove-outermost-parentheses
C++|faster code
cfaster-code-by-praduman_singh-5nci
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
praduman_Singh
NORMAL
2022-11-21T18:51:54.131563+00:00
2022-11-21T18:51:54.131599+00:00
810
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n\n# Code\n```\nclass Solution {\npublic:\n string removeOuterParentheses(string s) {\n string res="";\n stack<char> st;\n int i=0;\n while(i<s.size()){\n char ch = s[i];\n if(ch ==\'(\'){\n if(st.size()>0)\n res += ch;\n st.push(ch);\n }\n else{\n if(st.size()>1){\n res +=\')\';\n }\n st.pop();\n }\n \n\n i++;\n }\n return res;\n }\n};\n```
4
0
['String', 'Stack', 'C++']
0
remove-outermost-parentheses
JAVASCRIPT easy stepwise
javascript-easy-stepwise-by-ankitguria14-iv4o
\n let count = 0, outer = ""\n \n for(let i = 0 ; i < s.length; i++) {\n if(s[i] === "(") {\n count++\n }\n if(count >
ankitguria142
NORMAL
2022-03-13T17:10:46.477385+00:00
2022-03-13T17:10:46.477446+00:00
466
false
\n let count = 0, outer = ""\n \n for(let i = 0 ; i < s.length; i++) {\n if(s[i] === "(") {\n count++\n }\n if(count > 1) {\n outer += s[i]\n }\n if(s[i] === ")") {\n count--\n }\n }\n return outer\n
4
0
['JavaScript']
0
remove-outermost-parentheses
Java || Easy to understand
java-easy-to-understand-by-arabboyismoil-83ek
\nclass Solution {\n public String removeOuterParentheses(String s) {\n int count=0, start=0;\n StringBuilder res= new StringBuilder();\n
arabboyismoilov
NORMAL
2021-10-12T16:02:27.619348+00:00
2021-10-12T16:02:27.619392+00:00
377
false
```\nclass Solution {\n public String removeOuterParentheses(String s) {\n int count=0, start=0;\n StringBuilder res= new StringBuilder();\n \n for(int i=0; i<s.length(); i++){\n if(s.charAt(i)==\'(\')\n count++;\n else\n count--;\n\t\t\t\t\n if(count==0){\n res.append(s.substring(start+1,i));\n start=i+1;\n }\n }\n return res.toString();\n }\n}\n```
4
0
['Java']
2
remove-outermost-parentheses
Java solution 5 lines, faster and less memory than 99% (example also in C++, Python)
java-solution-5-lines-faster-and-less-me-mw2l
Although this problem is labeled as \'easy\' it can seem quite difficult at first, especially due to the way the writeup was written.\n\nHere is an advice, whic
Njall
NORMAL
2021-07-25T10:39:02.188027+00:00
2021-07-25T10:54:22.907909+00:00
147
false
Although this problem is labeled as \'easy\' it can seem quite difficult at first, especially due to the way the writeup was written.\n\nHere is an advice, which has always helped me break down parenthesis problems. There is something called Catalan structures or Catalan numbers. Now, bear with me! This might seem awfully complicated since Catalan numbers is something abstract and mathematical. But take a look at table 2 on page 2 in this paper:\n http://www.geometer.org/mathcircles/catalan.pdf\n\nSee these \'Mountain Ranges\'? These can be thought of as matches. Where you would add an upwards leaning match for an open parenthesis and a downwards leaning match for a closing parenthesis. Here is the important part: A Mountain range like this, where we start at the bottom and end at the bottom is a valid parenthesis.\n\nNow, if you draw on a piece of paper the three examples given in the write-up. You can see that the problem is only asking you to remove the lowest level of each \'mountain\'. Since that is the case, the only thing we need is a counter while we iterate through the characters forming the parenthesis string. For each level we go up (open parenthesis) we increment the counter while we decrement it while we go down. So you can think of the counter as keeping track of the elevation in the mountain range.\n\nNow, what I did in my solution was to initialize a counter and a string builder. Whenever there was an open parenthesis at levels other than zero I added the char to the string builder. Whenever there was a closing parenthesis at a level other than 1, I added the parenthesis to the string builder. This effectively removes the bottom level for each mountain in the mountain range\n\nWhy does this work? Try drawing it out!\n\n**Java**\n```\nclass Solution {\n public String removeOuterParentheses(String s) {\n StringBuilder sb = new StringBuilder();\n int count = 0;\n for(char c : s.toCharArray())\n if (c == \'(\' && count++ != 0) sb.append(c);\n else if (c == \')\' && count-- != 1) sb.append(c);\n return sb.toString();\n }\n}\n```\n\n**c++**\n```\nclass Solution {\npublic:\n string removeOuterParentheses(string s) \n \n int count = 0; // count elevation\n char output[s.length()]; // the output string\n int head = 0; // write head of buffer\n \n for(int i = 0; i < s.length(); i++){\n char c = s[i];\n if (c == \'(\' && count++ > 0) output[head++] = c;\n else if (c == \')\' && count-- > 1) output[head++] = c;\n }\n \n // null terminate the string and return\n output[head] = 0;\n return output;\n }\n};\n```\n\n**Python 3**\nNote that using an array, keeps the running time linear (amortized) appending strings would result in O(N^2)\n```\nclass Solution:\n def removeOuterParentheses(self, s: str) -> str:\n output = []\n count = 0\n for c in s:\n if c == \'(\':\n if count > 0: output.append(c)\n count += 1\n if c == \')\':\n if count > 1: output.append(c)\n count -= 1\n return "".join(output)\n```
4
0
[]
0
remove-outermost-parentheses
Simple Go and Java solutions
simple-go-and-java-solutions-by-nathanna-ulwl
Java:\n\n\npublic String removeOuterParentheses(String S) {\n\tStringBuilder s = new StringBuilder();\n\tStack<Character> h = new Stack<>();\n\n\tfor (int i = 0
nathannaveen
NORMAL
2021-02-01T15:04:27.637383+00:00
2021-02-01T15:04:27.637435+00:00
688
false
Java:\n\n```\npublic String removeOuterParentheses(String S) {\n\tStringBuilder s = new StringBuilder();\n\tStack<Character> h = new Stack<>();\n\n\tfor (int i = 0; i < S.length(); i++) {\n\t\tif (h.size() == 1 && S.charAt(i) == \')\'){\n\t\t\th.pop();\n\t\t\tcontinue;\n\t\t}\n\t\telse if (h.size() == 0 && S.charAt(i) == \'(\'){\n\t\t\th.push(\'(\');\n\t\t}\n\t\telse if (S.charAt(i) == \')\'){\n\t\t\ts.append(")");\n\t\t\th.pop();\n\t\t}\n\t\telse if (S.charAt(i) == \'(\'){\n\t\t\ts.append("(");\n\t\t\th.push(\'(\');\n\t\t}\n\t}\n\treturn s.toString();\n}\n```\n\nGolang:\n\n```\nfunc removeOuterParentheses(S string) string {\n\ts := ""\n\th := []string{}\n\n\tfor _, i2 := range S {\n\t\tif string(i2) == "(" {\n\t\t\tif len(h) != 0 {\n\t\t\t\ts += "("\n\t\t\t}\n\t\t\th = append(h, "(")\n\t\t} else {\n\t\t\tif len(h) != 1 {\n\t\t\t\ts += ")"\n\t\t\t}\n\t\t\th = h[:len(h)-1]\n\t\t}\n\t}\n\treturn s\n}\n```
4
0
['Java', 'Go']
0
remove-outermost-parentheses
Java solution with stack and explanation
java-solution-with-stack-and-explanation-gejp
This works because if the parentheses is outer most and it is a closing parenthese then the size of the stack has to be equal to one. If the parenthese is openi
nathannaveen
NORMAL
2020-12-10T14:40:35.708693+00:00
2021-08-08T13:44:50.098647+00:00
769
false
This works because if the parentheses is outer most and it is a closing parenthese then the size of the stack has to be equal to one. If the parenthese is opening then the size should be 0. Other wise they are inear parentheses.\n```\npublic String removeOuterParentheses(String S) {\n\tStringBuilder s = new StringBuilder();\n\tStack<Character> h = new Stack<>();\n\n\tfor (int i = 0; i < S.length(); i++) {\n\t\tif (h.size() == 1 && S.charAt(i) == \')\'){\n\t\t\th.pop();\n\t\t}\n\t\telse if (h.size() == 0 && S.charAt(i) == \'(\'){\n\t\t\th.push(\'(\');\n\t\t}\n\t\telse if (S.charAt(i) == \')\'){\n\t\t\ts.append(")");\n\t\t\th.pop();\n\t\t}\n\t\telse if (S.charAt(i) == \'(\'){\n\t\t\ts.append("(");\n\t\t\th.push(\'(\');\n\t\t}\n\t}\n\treturn s.toString();\n}\n```
4
0
['Stack', 'Java']
2
remove-outermost-parentheses
Easy way explanation every step
easy-way-explanation-every-step-by-paul_-l8bq
if your current char is \'(\' then two things happen one is stack is empty then don\'t add char in result means it indicates no outer parentheses is present.if
paul_dream
NORMAL
2020-11-14T06:35:22.549689+00:00
2020-11-14T06:53:35.656724+00:00
163
false
# if your current char is \'(\' then two things happen one is stack is empty then don\'t add char in result means it indicates no outer parentheses is present.if your stack is not empty then definitely have a outer parentheses this time add char into results\n```\nif c == \'(\':\n if stack:\n res.append(c)\n stack.append(c)\n\n```\n# when current char is ")" and popfrom a stack "(" .two things happen if your stack is empty it means no outer parentheses.if not empty then outer parentheses is present.so add into result .\n```\nelse:\n stack.pop()\n if stack:\n res.append(c)\n```\n# Easy example\n```\nYour input\n"()()()()"\nstdout\nposition= 0 current char= ( stack= []\nresult= \n\nposition= 1 current char= ) stack= [\'(\']\nresult= \n\nposition= 2 current char= ( stack= []\nresult= \n\nposition= 3 current char= ) stack= [\'(\']\nresult= \n\nposition= 4 current char= ( stack= []\nresult= \n\nposition= 5 current char= ) stack= [\'(\']\nresult= \n\nposition= 6 current char= ( stack= []\nresult= \n\nposition= 7 current char= ) stack= [\'(\']\nresult= \n\n\nOutput\n""\n\n\n```\n# simple Example\n```\nYour input\n"(())"\nstdout\nposition= 0 current char= ( stack= []\nresult= \n\nposition= 1 current char= ( stack= [\'(\']\nresult= (\n\nposition= 2 current char= ) stack= [\'(\', \'(\']\nresult= ()\n\nposition= 3 current char= ) stack= [\'(\']\nresult= ()\n\n\nOutput\n"()"\nExpected\n"()"\n```\n# hard example\n```\n"(((())))"\nstdout\nposition= 0 current char= ( stack= []\nresult= \n\nposition= 1 current char= ( stack= [\'(\']\nresult= (\n\nposition= 2 current char= ( stack= [\'(\', \'(\']\nresult= ((\n\nposition= 3 current char= ( stack= [\'(\', \'(\', \'(\']\nresult= (((\n\nposition= 4 current char= ) stack= [\'(\', \'(\', \'(\', \'(\']\nresult= ((()\n\nposition= 5 current char= ) stack= [\'(\', \'(\', \'(\']\nresult= ((())\n\nposition= 6 current char= ) stack= [\'(\', \'(\']\nresult= ((()))\n\nposition= 7 current char= ) stack= [\'(\']\nresult= ((()))\n\n\nOutput\n"((()))"\nExpected\n"((()))"\n```\n# complex example\n```\nYour input\n"(()())(())"\nstdout\nposition= 0 current char= ( stack= []\nresult= \n\nposition= 1 current char= ( stack= [\'(\']\nresult= (\n\nposition= 2 current char= ) stack= [\'(\', \'(\']\nresult= ()\n\nposition= 3 current char= ( stack= [\'(\']\nresult= ()(\n\nposition= 4 current char= ) stack= [\'(\', \'(\']\nresult= ()()\n\nposition= 5 current char= ) stack= [\'(\']\nresult= ()()\nposition= 6 current char= ( stack= []\nresult= ()()\n\nposition= 7 current char= ( stack= [\'(\']\nresult= ()()(\n\nposition= 8 current char= ) stack= [\'(\', \'(\']\nresult= ()()()\n\nposition= 9 current char= ) stack= [\'(\']\nresult= ()()()\n\nOutput\n"()()()"\nExpected\n"()()()"\n\n```\n\n```\n\nclass Solution(object):\n def removeOuterParentheses(self, S):\n """\n :type S: str\n :rtype: str\n """\n res,stack = [],[]\n for i,c in enumerate (S):\n \n if c == \'(\':\n if stack:\n res.append(c)\n stack.append(c)\n else:\n stack.pop()\n if stack:\n res.append(c)\n \n return \'\'.join(res)\n \n \n```
4
0
['Python']
0
remove-outermost-parentheses
Concept of these kind of problems | Simple |
concept-of-these-kind-of-problems-simple-iurm
problem similar to Google Hashcode 2020 Qualification round\nThe key in these types of problems is to have a variable named depth, and increment and decrement i
IamVaibhave53
NORMAL
2020-04-09T09:45:46.621622+00:00
2020-12-15T06:24:23.342552+00:00
150
false
problem similar to Google Hashcode 2020 Qualification round\nThe key in these types of problems is to have a variable named depth, and increment and decrement it accordingly [ \'(\' depth increases ] \nHere whenver the depth is currently zero we ignore it, and when it is again going to be zero after a series of open and closing parenthesis we ignore it again. \n\n```\nclass Solution {\npublic:\n string removeOuterParentheses(string S) {\n int depth=0;\n string p;\n for(int i=0;i<S.length();i++){\n if (S[i]==\'(\') {\n\t\t\t\tif (depth!=0){\n p+=\'(\';\n\t\t\t\t}\n depth+=1;\n\t\t\t}\n if (S[i]==\')\'){\n\t\t\t\tif (depth-1!=0){\n p+=\')\';\n\t\t\t\t}\n depth-=1;\n\t\t\t} \n }\n return p;\n }\n};
4
0
[]
2
remove-outermost-parentheses
C++ using stack
c-using-stack-by-leenabhandari1-eahv
\nclass Solution {\npublic:\n string removeOuterParentheses(string S) {\n stack<char> ss;\n string ans = "";\n \n for(char c: S)
leenabhandari1
NORMAL
2020-01-18T18:19:50.077714+00:00
2020-01-18T18:19:50.077763+00:00
259
false
```\nclass Solution {\npublic:\n string removeOuterParentheses(string S) {\n stack<char> ss;\n string ans = "";\n \n for(char c: S) {\n if(ss.empty() && c==\'(\') {\n ss.push(c);\n } else if(ss.size() == 1 && c==\')\') {\n ss.pop();\n } else if(c==\'(\') {\n ss.push(c);\n ans+=c;\n } else if(c==\')\') {\n ss.pop();\n ans+=c;\n }\n }\n \n return ans;\n }\n};\n```
4
0
[]
0
remove-outermost-parentheses
Haskell Wins! 1-liner
haskell-wins-1-liner-by-code_report-umh9
This is why Haskell is so beautiful:\n\nsolve :: String -> String\nsolve = concat \n . map (tail . init) \n . groupBy (\\a b -> [a,b] /= ")(")\n\nThe
code_report
NORMAL
2019-08-13T21:30:09.177325+00:00
2019-08-13T21:30:09.177366+00:00
526
false
This is why Haskell is so beautiful:\n```\nsolve :: String -> String\nsolve = concat \n . map (tail . init) \n . groupBy (\\a b -> [a,b] /= ")(")\n```\nThe one-liner would be:\n```\nsolve = concat . map (tail . init) . groupBy (\\a b -> [a,b] /= ")(")\n```
4
0
[]
0
remove-outermost-parentheses
python3 40ms beas 93%
python3-40ms-beas-93-by-jianquanwang-9xna
time complexity : O(n)\n\nclass Solution:\n def removeOuterParentheses(self, S: str) -> str:\n if len(S) <= 2:\n return ""\n \n
jianquanwang
NORMAL
2019-07-01T17:43:48.772567+00:00
2019-07-01T17:43:48.772623+00:00
167
false
time complexity : O(n)\n```\nclass Solution:\n def removeOuterParentheses(self, S: str) -> str:\n if len(S) <= 2:\n return ""\n \n ans = ""\n count = 0\n for c in S:\n if c == "(":\n count += 1\n if count > 1:\n ans += c\n else:\n count -= 1\n if count > 0:\n ans += c\n \n return ans\n```
4
0
[]
0
remove-outermost-parentheses
java solution
java-solution-by-user7409dy-gso1
\nclass Solution {\n public String removeOuterParentheses(String S) {\n if(S == null) return "";\n char[] chars = S.toCharArray();\n int
user7409dy
NORMAL
2019-06-22T06:26:48.069046+00:00
2019-06-22T06:26:48.069089+00:00
451
false
```\nclass Solution {\n public String removeOuterParentheses(String S) {\n if(S == null) return "";\n char[] chars = S.toCharArray();\n int stack = 0;\n\n StringBuilder builder = new StringBuilder();\n for(int i=0; i<chars.length; i++){\n if (chars[i] == 40) {\n stack ++;\n if(stack != 1) builder.append(chars[i]);\n } else if (chars[i] == 41) {\n stack --;\n if(stack != 0) builder.append(chars[i]);\n }\n }\n\n return builder.toString();\n }\n}\n```\n\n\nI use an \u201Cint stack\u201D to simulate the use of the stack.
4
0
[]
0
remove-outermost-parentheses
C++ solution using One stack and One queue.
c-solution-using-one-stack-and-one-queue-wx7s
\nclass Solution {\npublic:\n string removeOuterParentheses(string S) {\n stack<char> open;\n queue<char> primitive;\n string output;\n
hsuyaagnihotri
NORMAL
2019-04-07T05:42:11.626717+00:00
2019-04-07T05:42:11.626757+00:00
507
false
```\nclass Solution {\npublic:\n string removeOuterParentheses(string S) {\n stack<char> open;\n queue<char> primitive;\n string output;\n for(int i=0; i<S.length(); i++) {\n primitive.push(S[i]);\n if(S[i] == \'(\') {\n open.push(S[i]);\n }\n else {\n open.pop();\n if(open.empty()) {\n primitive.pop();\n while(!primitive.empty()) {\n output.push_back(primitive.front());\n primitive.pop();\n }\n output.pop_back();\n }\n }\n }\n return output;\n }\n};\n```\n\nStack stores the opening brackets. Once the stack is empty, we found one primitive. Primitives are stored in queue. We remove the outer brackets and store in output.
4
1
['C', 'C++']
1
remove-outermost-parentheses
java O(N) one scan no stack
java-on-one-scan-no-stack-by-noteanddata-grv7
http://www.noteanddata.com/leetcode-1021-Remove-Outermost-Parentheses-java-solution-note.html\n\n\n public String removeOuterParentheses(String S) {\n
noteanddata
NORMAL
2019-04-07T04:05:34.943455+00:00
2019-04-07T04:05:34.943497+00:00
511
false
http://www.noteanddata.com/leetcode-1021-Remove-Outermost-Parentheses-java-solution-note.html\n\n```\n public String removeOuterParentheses(String S) {\n int count = 0;\n int last = 0;\n StringBuilder sb = new StringBuilder();\n for(int i = 0; i < S.length(); ++i) {\n if(S.charAt(i) == \'(\') {\n count++;\n }\n else {\n count--;\n if(count == 0) {\n sb.append(S.substring(last+1, i));\n last = i + 1;\n }\n }\n }\n return sb.toString();\n }\n\n```
4
2
[]
0
consecutive-characters
[Python] One line
python-one-line-by-lee215-rw6l
\nPython:\npy\n def maxPower(self, s):\n return max(len(list(b)) for a, b in itertools.groupby(s))\n\n
lee215
NORMAL
2020-05-16T16:02:57.709396+00:00
2020-05-16T16:02:57.709453+00:00
5,699
false
\n**Python:**\n```py\n def maxPower(self, s):\n return max(len(list(b)) for a, b in itertools.groupby(s))\n```\n
79
6
[]
16
consecutive-characters
[Java/Python 3] Simple code w/ brief explanation and analysis.
javapython-3-simple-code-w-brief-explana-t9l1
Increase the counter by 1 if current char same as the previous one; otherwise, reset the counter to 1;\n2. Update the max value of the counter during each itera
rock
NORMAL
2020-05-16T16:04:25.965810+00:00
2022-05-01T01:26:52.094030+00:00
7,149
false
1. Increase the counter by 1 if current char same as the previous one; otherwise, reset the counter to 1;\n2. Update the max value of the counter during each iteration.\n\n```java\n public int maxPower(String s) {\n int ans = 1;\n for (int i = 1, cnt = 1; i < s.length(); ++i) {\n if (s.charAt(i) == s.charAt(i - 1)) {\n if (++cnt > ans) {\n ans = cnt;\n }\n }else {\n cnt = 1;\n }\n }\n return ans;\n }\n```\n```python\n def maxPower(self, s: str) -> int:\n cnt = ans = 1\n for i in range(1, len(s)):\n if s[i] == s[i - 1]:\n cnt += 1\n if cnt > ans:\n ans = cnt\n else:\n cnt = 1\n return ans\n```\n\n**Analysis:**\nTime: O(n), Space: O(1), where n = s.length().
76
0
[]
14
consecutive-characters
✅ [C++/Python] 3 Simple Solutions w/ Explanation | Brute-Force + Sliding Window + Single-Pass
cpython-3-simple-solutions-w-explanation-26bc
We need to return length of longest substring consisting of only one character\n\n---\n\n\u2714\uFE0F Solution - I (Brute-Force)\n\nWe can start at each charact
archit91
NORMAL
2021-12-13T02:43:51.958082+00:00
2021-12-13T07:35:08.064280+00:00
2,532
false
We need to return length of longest substring consisting of only one character\n\n---\n\n\u2714\uFE0F ***Solution - I (Brute-Force)***\n\nWe can start at each character in `s` and try to form longest substring from there which consists of only one character. If we find that the current character is not same as previous character of substring, we will break and update `ans` to store longest substring till now.\n\n**C++**\n```cpp\nclass Solution {\npublic:\n int maxPower(string& s) {\n int ans = 0;\n for(int i = 0; i < size(s); i++) {\n int j = i + 1;\n while(j < size(s) && s[j] == s[j-1]) // find longest substring starting at i\n j++;\n ans = max(ans, j-i); // ans holds length of longest substring containing same char\n }\n return ans;\n }\n};\n```\n\nOr a much concise implementation -\n\n```cpp\nclass Solution {\npublic:\n int maxPower(string& s, int ans = 1) {\n for(int i = 0, j; i < size(s); ans = max(ans, j - i++)) \n for(j = i+1; j < size(s) && s[j] == s[j-1]; j++);\n return ans;\n }\n};\n```\n\n**Python**\n```cpp\nclass Solution:\n def maxPower(self, s):\n ans = 1\n for i in range(len(s)):\n j = i + 1\n while j < len(s) and s[j] == s[j-1]:\n j += 1\n ans = max(ans, j-i)\n return ans\n```\n\n\n\n***Time Complexity :*** <code>O(N<sup>2</sup>)</code>, where `N` is the number of elements in `s`. For each element we expand substring starting at that element as long as possible. In the worst case of string containing all same character, we need to iterate till end for every element leading to TC of <code>O(N<sup>2</sup>)</code>\n***Space Complexity :*** `O(1)`\n\n---\n\n\u2714\uFE0F ***Solution - II (Sliding Window)***\n\nIn the previous approach, after finding the longest substring of same character starting at `i`th index, we were starting the next search from `i+1` th index. \n\nHowever, we dont need to start again from `i+1` and we can instead skip all indices which were already covered in the previous substring (since they would always result in smaller length substring as we are skipping 1st character from previous substring). This ensures that we only visit each character once and reduces time to linear runtime.\n\nThis approach can be considered as a kind of 2-pointer/sliding window approach where we are expanding right pointer of substring starting at `i` till we get same character and then moving to next window in the next iteration.\n\n**C++**\n```cpp\nclass Solution {\npublic:\n int maxPower(string& s) {\n int ans = 1;\n for(int i = 0; i < size(s); ) {\n int j = i + 1;\n while(j < size(s) && s[j] == s[j-1])\n j++;\n ans = max(ans, j-i);\n i = j; // ensures we dont repeat iteration over same element again\n }\n return ans;\n }\n};\n```\n\n\n<blockquote>\n<details>\n<summary><b><em>Concise Version</em></b></summary>\n\n```cpp\nclass Solution {\npublic:\n int maxPower(string& s, int ans = 1) {\n for(int i = 0, j=1; i < size(s); ans = max(ans, j-i), i = j++) \n for(; j < size(s) && s[j] == s[j-1]; j++);\n return ans;\n }\n};\n```\n</details>\n</blockquote>\n\n**Python**\n```python\nclass Solution:\n def maxPower(self, s):\n ans, i = 1, 0\n while i < len(s):\n j = i + 1\n while j < len(s) and s[j] == s[j-1]:\n j += 1\n ans = max(ans, j-i)\n i = j\n return ans\n```\n\n***Time Complexity :*** <code>O(N)</code>, each element is only visited once\n***Space Complexity :*** `O(1)`\n\n---\n\n\u2714\uFE0F ***Solution - III (One-Loop, Single-Pass)***\n\nWe can simplify the above implementation into single loop. \n* If current character is same as previous character, we will increment the consecutive character streak and update length of longest streak found till now into `ans`. \n* If current character is different than previous, we will reset the streak and start again at next iteration.\n\n**C++**\n```cpp\nclass Solution {\npublic:\n int maxPower(string& s) {\n int ans = 1, streak = 1;\n for(int i = 1; i < size(s); i++) \n if(s[i] == s[i-1]) ans = max(ans, ++streak); // same character => increment streak and update ans\n else streak = 1; // different character => reset consecutive streak\n return ans;\n }\n};\n```\n\n**Python**\n```python\nclass Solution:\n def maxPower(self, s):\n ans, streak = 1, 1\n for i in range(1, len(s)):\n if s[i] == s[i-1]:\n ans = max(ans, streak := streak + 1);\n else: streak = 1\n return ans\n```\n\n***Time Complexity :*** <code>O(N)</code>, each element is only visited once\n***Space Complexity :*** `O(1)`\n\n---\n---\n\n\uD83D\uDCBBIf there are any suggestions / questions / mistakes in my post, comment below \uD83D\uDC47 \n\n---\n---\n
45
4
[]
5
consecutive-characters
[Python] Oneliner using groupby, explained
python-oneliner-using-groupby-explained-nxj1u
What you need to do in this problem is just iterate over string and find groups of equal symbols, and then return the length of the longest group. Natural way t
dbabichev
NORMAL
2020-11-03T08:53:26.612272+00:00
2021-12-13T09:06:26.509373+00:00
992
false
What you need to do in this problem is just iterate over string and find groups of equal symbols, and then return the length of the longest group. Natural way to do it is to use functionality of itertools library, more precisely `groupby` function. By definition, if we do not specify arguments for groupby, it will create groups exactly with equal elements, so what we need to do is just to choose group with the biggest size and return it!\n\n**Complexity**: time and space complexity is `O(n)`, because we iterate over our data once, but also we need to have space to keep our groupby object.\n\n```\nclass Solution:\n def maxPower(self, s):\n return max(len(list(j)) for _, j in groupby(s))\n```\n\nIf you have any questions, feel free to ask. If you like solution and explanations, please **Upvote!**
32
2
[]
0
consecutive-characters
[JavaScript] Easy Sliding Window With Explanation & Analysis - O(n) time O(1) space
javascript-easy-sliding-window-with-expl-4fvj
Explanation:\n1. Increase the size of the window by incrementing the end index.\n2. After each increment, check if the size of the window (end - start + 1) is g
vine9
NORMAL
2020-05-16T18:50:48.004653+00:00
2020-05-16T19:48:03.298536+00:00
1,205
false
**Explanation:**\n1. Increase the size of the window by incrementing the end index.\n2. After each increment, check if the size of the window ```(end - start + 1)``` is greater than the current max size (power). \n3. Repeat steps 1 and 2 until the start and end characters of the window are no longer equal, then move to the start index to the same position as the end index to begin checking the next substring with unique characters.\n\n**Solution:**\n```javascript\nvar maxPower = function(s) {\n let power = 1\n \n let start = 0\n for (let end = 1; end < s.length; end++) {\n if (s[start] !== s[end]) {\n start = end\n }\n \n power = Math.max(power, end - start + 1)\n }\n \n return power\n};\n```\n\n**Complexity:**\n* Time: O(n) where n = s.length\n* Space: O(1)
18
0
['JavaScript']
1
consecutive-characters
[C++] 2 Pointers Optimised Solution Discussed and Explained, 100% Time, 100% Space
c-2-pointers-optimised-solution-discusse-2rrq
This problem is basically asking us to find the longest substring with a given condition - all the characters being the same.\n\nAnd while there are countless s
ajna
NORMAL
2020-11-03T10:31:53.755158+00:00
2020-11-03T10:39:03.846461+00:00
2,109
false
This problem is basically asking us to find the longest substring with a given condition - all the characters being the same.\n\nAnd while there are countless substring problems and even more so approaches you might use to solve them, this one is particularly suited for a straightforward approach using 2 pointers - one that will be "stuck" at the first new character we encounter, the other one advancing from there as long as we find chars with the same value.\n\nTo solve this problem, Iet\'s start as usual declaring a few variables, all `int`s:\n* `res`, to store the value of the maximum length found so far; you might initialise it to `1`, since the specs clearly state we will have at least one char, but I preferred to keep things more "flexible" and proper setting it to `0`;\n* `i` and `j` are our pointers and we start with `i == 0`;\n* `len` is the length of the initial string;\n* `curr` is the tricky one - it will store the value of the currently checked character (treated as an interger, but we really do not care); you might have avoided it and always used `s[i]` in its stead, but I preferred to avoid accessing it by indexing and found that it makes our code a big cleaner (try to always keep an interviewer behind the back of your mind - a good thought to keep both your guard and discipline up!). I will initialise it to the value of `s[0]`.\n\nWe will then proceed with an external loop going on as long as `i < len`. Inside it, we will:\n* set `j` to point to the next successive character, at `i + 1`;\n* increase the value of `j` as long as it does not go overflowing (`j < len`) and as long as it is pointing to characters with the same value of the character `i` points (`curr == s[j]`);\n* update `res` with this new interval\'s length, if greater than the currently stored value (`max(res, j - i)`);\n* set both `curr` and `i` for the next loop, respectively with the value of the next new character to parse (`s[j]`) and its pointer (`j`).\n\nSome thoughts of my approach: I know some people would rather increment a counter variable as long as `curr == s[j]`, but that is IMHO not the best approach, since you would do one extra operation (although it is a cheap incrementation of an integer) at each step: in extreme cases, that approach would do, say, 500 increment operations if you had a string made only of 500 `\'a\'` versus our approach that would just computer `j - i` at the end - that is 499 more operations for you!\n\nNow, while it might seem trivial with the string length limit for this specific problem, in my book every unnecessary operation tha does not carry any value at all (even it is was just readability), just gets cut out and stays on the floor, that is why I opted to proceed as I did.\n\nOnce done, we return `res` :)\n\nThe code:\n\n```cpp\nclass Solution {\npublic:\n int maxPower(string s) {\n // support variables\n int res = 0, i = 0, j, len = s.size(), curr = s[0];\n while (i < len) {\n // updating j\n j = i + 1;\n // moving j to the first value of s[j] != curr\n while (j < len && curr == s[j]) j++;\n // updating res\n res = max(res, j - i);\n // setting curr and i for the next loop\n curr = s[j];\n i = j;\n }\n return res;\n }\n};\n```
17
0
['Two Pointers', 'C', 'C++']
5
consecutive-characters
C++ EASY TO SOLVE || Beginner Friendly with a detailed explanation || Time-O(n) and Space-O(1)
c-easy-to-solve-beginner-friendly-with-a-y23w
Two Pointer Approach || Time-O(n) and Space-O(1)\n\nIntuition:\nAfter reading this question we got the gist ,that we need to find out the longest consecutive ch
Cosmic_Phantom
NORMAL
2021-12-13T02:14:59.931447+00:00
2024-08-23T02:43:12.683528+00:00
1,136
false
# **Two Pointer Approach || Time-O(n) and Space-O(1)**\n\n**Intuition:**\nAfter reading this question we got the gist ,that we need to find out the longest consecutive character sequence of same letter\n\n*For example:*\n```\nInput: s = "abbcccddddeeeeedcba"\nOutput: 5\nExplanation: The substring "eeeee" is of length 5 with the character \'e\' only.\n```\nSo to solve this we will use two pointers approach one pointer for the starting letter and second pointer for the last letter of the sequence. Actually we can also make it a one pointer approach by adjusting the tempcount in the loop . But since both the approach will have same time complexity and space complexity we will be using two pointer approach since it\'s easy to understand.\n\n**Algorithm:**\n1. Let the two pointer\'s be `tempcount` which stores the current sequence of same characters that we are iterating and `maxcount` be the consecutive maxsequence of same characters we iterated till now\n2. We also have a base case i.e If the input string has only one letter than return 1 \n3. Now traverse the whole string and compare the consecutive letters if found same than increment the `tempcount` .\n4. After the new `tempcount` , compare it with `maxcount` & if `tempcount` is greater than `maxcount` then assign it to `maxcount` . \n5. The process 3 and 4 repeats till the end of the string\n\n**Code:-**\n```\n//Upvote and Comment\nclass Solution {\npublic:\n int maxPower(string s) {\n //tempcount-for currnet sequence , maxcount-for the maxsequence we iterated till now\n int tempCount = 1,maxcount = 1,i=1;\n //base case\n if(s.length()==1) return 1;\n //Loop till the end of the string\n while(s[i]!=\'\\0\'){\n //comparing the consecutive characters\n if(s[i-1]==s[i]) tempCount++;\n else tempCount = 1;\n //if tempcount has more same charaters than maxcount, assign it to maxcount\n if(maxcount < tempCount) maxcount = tempCount;\n i++;\n }\n return maxcount;\n }\n};\n```\n**Time Compplexity : O(n) [Takes one pass only]\nSpace Complexity : O(1)**\n
16
9
['Two Pointers', 'C', 'C++']
1
consecutive-characters
easy faster than 90% cpp solution
easy-faster-than-90-cpp-solution-by-jink-m937
\nclass Solution {\npublic:\n int maxPower(string s) {\n size_t max = 1;\n size_t curr = 1;\n for (size_t i = 1; i < s.size(); i++) {\n
jinkim
NORMAL
2020-06-26T22:06:57.241649+00:00
2020-06-26T22:06:57.241698+00:00
1,329
false
```\nclass Solution {\npublic:\n int maxPower(string s) {\n size_t max = 1;\n size_t curr = 1;\n for (size_t i = 1; i < s.size(); i++) {\n if (s[i - 1] == s[i]) curr++;\n else {\n if (curr > max) max = curr;\n curr = 1;\n }\n }\n if (curr > max) max = curr; // edge case\n return max;\n }\n};\n```
12
0
['C', 'C++']
2
consecutive-characters
C++ Super Easy, Short and Simple One-Pass Solution
c-super-easy-short-and-simple-one-pass-s-r4nt
\nclass Solution {\npublic:\n int maxPower(string s) {\n int max_len = 0, curr_len = 0;\n char prev = s[0];\n \n for (auto letter
yehudisk
NORMAL
2021-12-13T09:04:15.715178+00:00
2021-12-13T09:04:15.715222+00:00
1,054
false
```\nclass Solution {\npublic:\n int maxPower(string s) {\n int max_len = 0, curr_len = 0;\n char prev = s[0];\n \n for (auto letter : s){\n if (letter == prev)\n curr_len++;\n else\n curr_len = 1;\n \n max_len = max(max_len, curr_len);\n prev = letter;\n }\n \n return max_len;\n }\n};\n```\n**Like it? please upvote!**
11
3
['C']
1
consecutive-characters
Python O(n) by linear scan. [w/ Comment]
python-on-by-linear-scan-w-comment-by-br-ifwf
Python O(n) by linear scan.\n\n---\n\n\nclass Solution:\n def maxPower(self, s: str) -> int:\n \n # the minimum value for consecutive is 1\n
brianchiang_tw
NORMAL
2020-05-17T13:57:38.917815+00:00
2020-05-17T13:57:38.917858+00:00
1,792
false
Python O(n) by linear scan.\n\n---\n\n```\nclass Solution:\n def maxPower(self, s: str) -> int:\n \n # the minimum value for consecutive is 1\n local_max, global_max = 1, 1\n \n # dummy char for initialization\n prev = \'#\'\n for char in s:\n \n if char == prev:\n \n # keeps consecutive, update local max\n local_max += 1\n \n # update global max length with latest one\n global_max = max( global_max, local_max )\n \n else:\n \n # lastest consective chars stops, reset local max\n local_max = 1\n \n # update previous char as current char for next iteration\n prev = char\n \n \n return global_max\n```
11
0
['String', 'Iterator', 'Python', 'Python3']
5
consecutive-characters
[Java] O(n) time O(1) space
java-on-time-o1-space-by-manrajsingh007-mnfp
```\nclass Solution {\n public int maxPower(String s) {\n int n = s.length();\n int start = 0, end = 0, max = 0;\n while(end < n) {\n
manrajsingh007
NORMAL
2020-05-16T16:00:59.562341+00:00
2020-05-16T16:07:30.203630+00:00
1,656
false
```\nclass Solution {\n public int maxPower(String s) {\n int n = s.length();\n int start = 0, end = 0, max = 0;\n while(end < n) {\n while(end < n && s.charAt(end) == s.charAt(start)) {\n max = Math.max(max, end - start + 1);\n end++;\n }\n if(end == n) return max;\n start = end;\n }\n return max;\n }\n}
11
3
[]
0
consecutive-characters
Easy python solution
easy-python-solution-by-vistrit-tm6k
\ndef maxPower(self, s: str) -> int:\n c,ans = 1,1\n for i in range(len(s)-1):\n if s[i]==s[i+1]:\n c+=1\n
vistrit
NORMAL
2021-12-13T07:11:06.708362+00:00
2021-12-13T07:11:06.708395+00:00
1,374
false
```\ndef maxPower(self, s: str) -> int:\n c,ans = 1,1\n for i in range(len(s)-1):\n if s[i]==s[i+1]:\n c+=1\n ans=max(c,ans)\n else:\n c=1\n return ans\n```
9
0
['Python', 'Python3']
1
consecutive-characters
Java Simple Approach O(n) Time, O(1) Space
java-simple-approach-on-time-o1-space-by-sekx
If next character is same increase the current counter. Else reset the current counter to 1 when a different character is encountered. \n\nclass Solution {\n
danielrechey28
NORMAL
2020-05-16T16:07:42.430657+00:00
2020-05-16T16:19:57.014277+00:00
1,210
false
If next character is same increase the current counter. Else reset the current counter to 1 when a different character is encountered. \n```\nclass Solution {\n public int maxPower(String s) {\n int len=s.length();\n int count =0;\n int curr=1;\n for(int i=0;i<len;i++){\n if(i<len-1 &&s.charAt(i) == s.charAt(i+1)){\n curr++;\n }\n else{\n if(curr>count){\n count = curr;\n }\n curr=1;\n }\n } \n return count; \n }\n```\n}
8
0
['Java']
0
consecutive-characters
EASIEST APPROACH 🤤||✅ 💯% ON RUNTIME ||✌️😎 WITH EXPLNATION
easiest-approach-on-runtime-with-explnat-t96j
Intuition\nThe problem asks to find the maximum consecutive occurrences of the same character in the given string s.\n\n# Approach\nWe can iterate through the c
IamHazra
NORMAL
2024-03-01T13:48:54.507813+00:00
2024-03-01T13:48:54.507838+00:00
281
false
# Intuition\nThe problem asks to find the maximum consecutive occurrences of the same character in the given string `s`.\n\n# Approach\nWe can iterate through the characters of the string `s` and keep track of the count of consecutive occurrences of the same character. We use two variables, `count` to keep track of the current count of consecutive occurrences and `max` to store the maximum count encountered so far. If the current character is the same as the previous one, we increment the count and update the maximum count. If the current character is different from the previous one, we reset the count to zero. Finally, we return the maximum count plus one because the count represents the number of consecutive occurrences of the same character, and adding one accounts for the current character itself.\n\n# Complexity\n- Time complexity: \\( O(n) \\), where \\( n \\) is the length of the input string `s`. We iterate through the string once to calculate the maximum consecutive occurrences.\n \n- Space complexity: \\( O(n) \\), where \\( n \\) is the length of the input string `s`. We use an array of characters to store the characters of the string.\n\n# Code\n```java\nclass Solution {\n public int maxPower(String s) {\n int count = 0; \n int max = 0; \n char[] array = s.toCharArray(); \n \n for (int i = 1; i < s.length(); i++) {\n if (array[i - 1] == array[i]) {\n count++; \n max = Math.max(max, count); \n } else {\n count = 0; \n }\n }\n \n return max + 1;\n }\n}\n```
7
0
['String', 'Counting', 'Java']
1
consecutive-characters
[C++] One Pass
c-one-pass-by-orangezeit-7lk3
cpp\nclass Solution {\npublic:\n int maxPower(string s) {\n int ans(1), k(0);\n s += \'*\';\n for (int i = 0; i + 1 < s.length(); ++i)\n
orangezeit
NORMAL
2020-05-16T16:20:32.600311+00:00
2020-05-16T16:20:32.600346+00:00
1,056
false
```cpp\nclass Solution {\npublic:\n int maxPower(string s) {\n int ans(1), k(0);\n s += \'*\';\n for (int i = 0; i + 1 < s.length(); ++i)\n if (s[i] != s[i + 1]) {\n ans = max(ans, i + 1 - k);\n k = i + 1;\n }\n return ans;\n }\n};\n```
7
1
[]
0
consecutive-characters
Easy c++ solution with comments
easy-c-solution-with-comments-by-sarnava-akqu
\nclass Solution {\npublic:\n int maxPower(string s) {\n //ans will store the final ans and now will store the current answer\n int ans = INT_M
sarnava
NORMAL
2020-05-16T16:07:21.405661+00:00
2020-05-16T16:19:58.874479+00:00
549
false
```\nclass Solution {\npublic:\n int maxPower(string s) {\n //ans will store the final ans and now will store the current answer\n int ans = INT_MIN, now = 1;\n \n for(int i = 0;i<s.length();i++){\n //if the current char is the same as the next char then increase now\n if(i+1<s.length()&&s[i]==s[i+1]){\n now++;\n }else{\n //if the 2 consecutive characters are not same then update ans\n ans = max(ans,now);\n //assign 1 to now to store the count for the next consecutive chars\n now = 1; \n }\n }\n //return ans as the final answer\n return ans;\n }\n};\n```
7
1
[]
1
consecutive-characters
Java | 100% Faster | Explained | Simplest Solution | O(N)
java-100-faster-explained-simplest-solut-xgrp
We will be checking if subsequent characters are equal, if yes we will keep on incrementing the count otherwise we will store the new value in max if count > ma
rounak2k
NORMAL
2021-12-13T05:39:40.357608+00:00
2021-12-13T06:04:17.671833+00:00
1,030
false
We will be checking if subsequent characters are equal, if yes we will keep on incrementing the count otherwise we will store the new value in max if count > max.\n```\nclass Solution {\n public int maxPower(String s) {\n\t\t// Taking max & count as 1 since minimum length of substring can be 1\n int max = 1, count = 1;\n for(int i=0;i<s.length()-1;i++) {\n if(s.charAt(i)!=s.charAt(i+1)) {\n\t\t\t\t// If the subsequent characters are not equal, then compare the count with max & update if required\n max = Math.max(max, count);\n\t\t\t\t// Reset count as 1, to check on remaining string\n count = 1;\n continue;\n }\n else\n count ++;\n } \n\t\t// Incase of "abcc", max = 1, but count = 2, so we will be returning the max of them\n return Math.max(max, count);\n }\n}\n```
6
1
['Java']
4
consecutive-characters
Clean JavaScript Solution
clean-javascript-solution-by-shimphillip-bpgj
\n// time O(n^2) space O(1)\nvar maxPower = function(s) {\n let max = 1\n let count = 1\n \n for(let i=0; i<s.length - 1; i++) {\n if(s[i] ==
shimphillip
NORMAL
2020-11-10T21:55:34.175930+00:00
2020-12-03T04:07:28.764713+00:00
572
false
```\n// time O(n^2) space O(1)\nvar maxPower = function(s) {\n let max = 1\n let count = 1\n \n for(let i=0; i<s.length - 1; i++) {\n if(s[i] === s[i+1]) {\n count++\n max = Math.max(count, max)\n } else {\n count = 1\n }\n }\n \n return max\n};\n```\n
6
0
['JavaScript']
1
consecutive-characters
simple and easy understanding c++ code
simple-and-easy-understanding-c-code-by-6qzla
\ncpp []\nclass Solution {\npublic:\n int maxPower(string s) {\n int n=s.length();\n int c=1,d=1;\n if(n==0){\n return 0;\n
sampathkumar718
NORMAL
2024-09-19T17:18:55.802857+00:00
2024-09-19T17:18:55.802882+00:00
197
false
\n```cpp []\nclass Solution {\npublic:\n int maxPower(string s) {\n int n=s.length();\n int c=1,d=1;\n if(n==0){\n return 0;\n }\n for(int i=1;i<n;i++){\n if(s[i]==s[i-1]){\n c++;\n }\n else{\n d=max(d,c);\n c=1;\n }\n\n }\n d=max(c,d);\n return d;\n \n }\n};\n```
5
0
['C++']
0
consecutive-characters
Python ✅✅✅ || Faster than 99.60% || Memory Beats 97.63%
python-faster-than-9960-memory-beats-976-ttym
Code\n\nclass Solution:\n def maxPower(self, s):\n cnt = 0\n m = 0\n for i in range(1, len(s)):\n if (s[i-1] == s[i]): \n
a-fr0stbite
NORMAL
2022-12-15T02:49:10.106544+00:00
2022-12-15T02:49:10.106586+00:00
527
false
# Code\n```\nclass Solution:\n def maxPower(self, s):\n cnt = 0\n m = 0\n for i in range(1, len(s)):\n if (s[i-1] == s[i]): \n cnt += 1\n m = max(cnt, m)\n else: cnt = 0\n return m + 1\n```\n![image.png](https://assets.leetcode.com/users/images/6c285c86-bf64-44be-8c02-519334d6dbdd_1671072367.0797808.png)\n![image.png](https://assets.leetcode.com/users/images/2b36c6e8-594a-49d7-8876-1ccd2b9f2e89_1671072410.3246603.png)\n
5
1
['Python3']
1
consecutive-characters
Daily LeetCoding Challenge [13 December 2021] in C++
daily-leetcoding-challenge-13-december-2-u3a0
\nSolution in c++\n\n\n\nclass Solution {\npublic:\n int maxPower(string s) {\n int n = s.size();\n int ans = 1;\n int cnt = 1;\n
spyder_master
NORMAL
2021-12-13T04:56:47.696444+00:00
2021-12-14T05:28:06.176771+00:00
145
false
\n**Solution in c++**\n\n\n```\nclass Solution {\npublic:\n int maxPower(string s) {\n int n = s.size();\n int ans = 1;\n int cnt = 1;\n for(int i = 1; i < n; i++){\n if(s[i] == s[i-1]){\n cnt++;\n }else{\n cnt = 1;\n }\n ans = max(ans, cnt);\n }\n return ans; \n }\n};\n\n```\n\n**if you understand solution then dont forget to upvote**
5
0
['String', 'C']
0
consecutive-characters
[Rust] solution
rust-solution-by-rudy-41h4
There is no magic here, just iterate over the string and count the length of consecutive substring. \n\n### Rust Solution\nRust\nimpl Solution {\n pub fn max
rudy__
NORMAL
2020-05-17T05:37:10.545551+00:00
2022-11-19T02:53:18.054120+00:00
100
false
There is no magic here, just iterate over the string and count the length of consecutive substring. \n\n### Rust Solution\n```Rust\nimpl Solution {\n pub fn max_power(s: String) -> i32 {\n let (mut res, mut cnt) = (0, 0);\n let mut pre = \'#\' ;\n for c in s.chars() {\n if c == pre {\n cnt += 1; \n res = std::cmp::max(res, cnt);\n } else {\n pre = c;\n cnt = 1;\n }\n }\n max(res, 1) \n }\n}\n```
5
0
[]
1
consecutive-characters
Simple java - 5 lines - O(n) time and O(1) space
simple-java-5-lines-on-time-and-o1-space-47k5
\n public int maxPower(String s) {\n int res = 0, n = s.length();\n for(int i=0; i<n; i++){\n int j = i;\n\t\t\twhile(i+1 < n && s.c
ijaz20
NORMAL
2020-05-16T16:02:22.755542+00:00
2020-05-16T17:21:08.028776+00:00
319
false
```\n public int maxPower(String s) {\n int res = 0, n = s.length();\n for(int i=0; i<n; i++){\n int j = i;\n\t\t\twhile(i+1 < n && s.charAt(i) == s.charAt(i+1)) {i++;} \n res = Math.max(i-j+1, res);\n }\n return res;\n }\n```
5
12
[]
0
consecutive-characters
💢☠💫Easiest👾Faster✅💯 Lesser🧠 🎯 C++✅Python3🐍✅Java✅C✅Python🐍✅C#✅💥🔥💫Explained☠💥🔥 Beats 100
easiestfaster-lesser-cpython3javacpython-fp8l
Intuition\n\n Describe your first thoughts on how to solve this problem. \n- JavaScript Code --> https://leetcode.com/problems/consecutive-characters/submission
Edwards310
NORMAL
2024-09-03T09:57:44.177482+00:00
2024-09-03T09:57:44.177509+00:00
486
false
# Intuition\n![0ehh83fsnh811.jpg](https://assets.leetcode.com/users/images/966cc9ff-60a8-45b0-86df-a792241eab1a_1725356745.7222025.jpeg)\n<!-- Describe your first thoughts on how to solve this problem. -->\n- ***JavaScript Code -->*** https://leetcode.com/problems/consecutive-characters/submissions/1377518875\n- ***C++ Code -->*** https://leetcode.com/problems/consecutive-characters/submissions/1377391724\n- ***Python3 Code -->*** https://leetcode.com/problems/consecutive-characters/submissions/1377471507\n- ***Java Code -->*** https://leetcode.com/problems/consecutive-characters/submissions/1377466619\n- ***C Code -->*** https://leetcode.com/problems/consecutive-characters/submissions/1377490145\n- ***Python Code -->*** https://leetcode.com/problems/consecutive-characters/submissions/1377469342\n- ***C# Code -->*** https://leetcode.com/problems/consecutive-characters/submissions/1377501664\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(1)\n# Code\n```javascript []\n/**\n * @param {string} s\n * @return {number}\n */\nvar maxPower = function (s) {\n var maclen = 0, currlen = 0\n let curr_ch = \'\\0\'\n for (let ch of s) {\n if (ch == curr_ch)\n currlen++\n else {\n curr_ch = ch\n currlen = 1\n }\n maclen = Math.max(maclen, currlen)\n }\n return maclen\n};\n```\n![th.jpeg](https://assets.leetcode.com/users/images/4826a03c-2f30-4322-9665-e57a0499369b_1725357445.7444794.jpeg)\n
4
0
['String', 'C', 'Python', 'C++', 'Java', 'Python3', 'JavaScript', 'C#']
0
consecutive-characters
C++ easy sol
c-easy-sol-by-richach10-xztw
\nclass Solution {\npublic:\n int maxPower(string s) {\n int maxi=1;\n int count=1;\n for(int i=1;i<s.size();i++){\n if(s[i]=
Richach10
NORMAL
2022-04-25T23:23:20.540775+00:00
2022-04-25T23:23:20.540803+00:00
273
false
```\nclass Solution {\npublic:\n int maxPower(string s) {\n int maxi=1;\n int count=1;\n for(int i=1;i<s.size();i++){\n if(s[i]==s[i-1]){\n count++;\n }\n else{\n count=1;\n }\n maxi=max(maxi,count); \n }\n return maxi; \n }\n};\n```
4
0
['C', 'C++']
0
consecutive-characters
JavaScript solution, faster than 97.78%
javascript-solution-faster-than-9778-by-ftid7
\nvar maxPower = function(s) {\n let maxStr = 1;\n let accum = 0;\n for (let i = 0; i < s.length; i++) {\n if (s[i] === s[i + 1]) {\n
art_litvenko
NORMAL
2021-12-13T10:34:55.840281+00:00
2021-12-14T18:42:18.953378+00:00
403
false
```\nvar maxPower = function(s) {\n let maxStr = 1;\n let accum = 0;\n for (let i = 0; i < s.length; i++) {\n if (s[i] === s[i + 1]) {\n maxStr += 1;\n } else {\n maxStr = 1;\n }\n if (maxStr > accum) {\n accum = maxStr;\n }\n }\n\n return accum;\n};\n```
4
0
['JavaScript']
0