Easiest and Clean C++ Sol |  No stack-Direct sol | Beats 97.2% Users | Easiest Explanation
Intuition\n\n\n Describe your first thoughts on how to solve this problem. \nWe remove unnecessary parentheses by iterating through the string twice: first loop
# Intuition\n![6 april potd.png](https://assets.leetcode.com/users/images/e3cea6e3-62a2-4322-b7de-c9dc69ae2352_1712383491.5429966.png)\n\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe remove unnecessary parentheses by iterating through the string twice: first loop to remove excess closing parentheses,second loop to remove extra opening parentheses.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n   - Initialize an empty string `temp`, which will store the processed string without unnecessary closing parentheses, and a counter `open` for tracking open parentheses.\n   - Iterate through each character in the input string `s`.\n     - If the character is \'(\', add it to `temp` and increment `open`.\n     - If the character is \')\' and there are open parentheses (i.e., `open > 0`), add it to `temp` and decrement `open`.\n     - If the character is neither \'(\' nor \')\', add it directly to `temp`.\n   - After the first pass, `temp` contains a string with balanced parentheses and no extra closing parentheses.\n   - Iterate through `temp` in reverse order (so that the opening parenthesis without having corresponding closing parenthesis come first ):\n     - If an opening parentheses \'(\' is encountered and there are still unmatched open parentheses (`open > 0`), decrement `open`.\n     - Otherwise, add the character to the final answer string `ans`.\n   - Reverse `ans` and return it as the result.\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# Please UPVOTE if you like it : )\n\n# Code\n```\nclass Solution {\npublic:\n    string minRemoveToMakeValid(string s) {\n        ios_base::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL);\n\n        string temp="",ans="";\n        int open=0;\n        for(int i=0;i<s.size();i++){\n            if(s[i]==\'(\')temp+=s[i],open++;\n            else if(s[i]==\')\' && open>0)temp+=s[i],open--;\n            else if(s[i]!=\'(\' && s[i]!=\')\')temp+=s[i];\n        }\n        for(int i=temp.size()-1;i>=0;i--){\n            if(temp[i]==\'(\' && open>0)open--;\n            else ans+=temp[i];\n        }\n        reverse(ans.begin(),ans.end());\n        return ans;    \n    }\n};\n\n```\n![THIS IS BILL.png](https://assets.leetcode.com/users/images/0a68f1fb-27eb-4d01-8c2b-88afba1c43cc_1712383405.9202788.png)\n
['C++']