C++ | Sharing my O(1) Space Complexity
The ideia here it\'s to do all the operations in-place of the string s. \n\nLet\'s divide the problem in three steps:\n\t1.  Mark all the extra closing parenthe
The ideia here it\'s to do all the operations in-place of the string `s`. \n\nLet\'s divide the problem in three steps:\n\t1.  Mark all the extra closing parenthesis to be removed in the future, changing the values to a space.\n\t2.  Mark all the extra opening parenthesis to be remover in the future, changing the values to a space.\n\t3.  Erase the spaces in the string `s`, moving the non-space chars to the left.\n\n\n```\nclass Solution {\nprivate:\n    void removeInvalid(string &s, char open, char close)\n    {\n        int count = 0;\n\n        for (auto &curr : s)\n        {\n            if (curr == open)\n                count++;\n            else if (curr != close)\n                continue;\n            else if (count == 0)\n                curr = \' \';\n            else\n                count--;\n        }\n    }\npublic:\n    string& minRemoveToMakeValid(string &s) {\n        //"Removing" the extra closing parenthesis.\n        removeInvalid(s, \'(\', \')\');\n        reverse(s.begin(), s.end());\n\n        //"Removing" the extra opening parenthesis.\n        removeInvalid(s, \')\', \'(\');\n        reverse(s.begin(), s.end());\n\n        //Removing the extra spaces in the string\n        int lastIndex = 0;\n        for (auto curr : s)\n            if (curr != \' \')\n                s[lastIndex++] = curr;\n\n        //Removing the extra chars remaing in the end\n        s.resize(lastIndex);\n\n        return s;\n    }\n};\n```
[]