C++ | Stack | From Brute Force to Optimized | Well Documented
Brute Force time-complexity : O(N(N+M))\nTypically O(N^2)\n\n\nclass Solution {\npublic:\n\tstring removeDuplicates(string s) {\n        int i = 0;\n        int
Brute Force time-complexity : O(N(N+M))\nTypically O(N^2)\n\n```    \nclass Solution {\npublic:\n\tstring removeDuplicates(string s) {\n        int i = 0;\n        int j = 1;\n        while(j < s.length()){\n            if(s[i] == s[j]){\n                s.erase(s.begin()+i);  // this function takes O(N+M) time\n                s.erase(s.begin()+i); // N is size of the array & M is the remaining elements to be shifted\n                i = 0;\n                j = 1;\n            }else{\n                i++;\n                j++;\n            }\n        }\n        return s;\n\t}\n}\n```\n\nOptimized time-complexity : O(N)\n```\nclass Solution {\npublic:\n\tstring removeDuplicates(string s) {\n\t    string ans ="";\n        stack<char> st;\n        for(int i = 0; i < s.length(); i++){\n            if(st.empty()){ // initially if the stack is empty (to avoid segmentation fault)\n                st.push(s[i]);\n                continue; \n            }else{\n                if(st.top() == s[i]){\n                    st.pop();\n                }else{\n                    st.push(s[i]);\n                }\n            }\n        }\n\t\t\n\t\t// popping out remaining elements and storing them to the string\n        while(!st.empty()){\n            ans.push_back(st.top());\n            st.pop();\n        }\n\t\t\n\t\t// reversing the string because stack reversed the string while popping.\n        reverse(ans.begin(), ans.end());\n\n        return ans;\n    }\n};\n```\n\nIf you read it till here don\'t forget to like :)
['Stack', 'C', 'C++']