Python // C++ // Haskell Solutions
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
**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
['C', 'Python']