✅Easy✨||C++ || Beats 100% || With Stack Approach Explained
Intuition\n Describe your first thoughts on how to solve this problem. \nThis question can be solved with loop and recursion but by using stack we will be using
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis question can be solved with loop and recursion but by using stack we will be using greedy method. So we will implement the stack here.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Iterate the loop over character one by one by the condition that if stack is not empty and and if top element will be equal to the char we are iterating then we will simply pop it.\n2. Otherwise we will just push that character and move on to another one \n3. We have created string of ans which will be used when we removed all the duplicate elements and then starts to add the string in ans and return it as output.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N) For one pass\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(N) For output\n# Code\n```\nclass Solution {\npublic:\n    string removeDuplicates(string s) {\n        stack<char>st;\n        for(auto ch:s) {\n            if(!st.empty() && st.top() == ch) {\n                //pair up the becacuse its duplicate\n                st.pop();\n            }\n            else{\n                st.push(ch);\n            }\n        } \n\n        string ans;\n        while(!st.empty()) {\n            ans += st.top();\n            st.pop();\n        }\n        reverse(ans.begin(), ans.end());\n        return ans;\n    }\n};\n```
['C++']