c++ beats 100% ✅ | with explaination | O(n) time, O(1) space
Intuition\nOpening parenthesis decreases the counter and closing parenthesis increases the counter\n\n   (  (  )  (  ) )  (  (  ) )\n0 -1 -2 -1 -2 -1 0 -1 -2 -1
# 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
['C++']