Optimized solution 🔥 Easy C++ 🔥 Stack implementation 🔥 st
PLEASE UPVOTE \uD83D\uDC4D\n# Approach \n### Simple implementation of stacks and because of circular array we take 2*n elements instead of n elements\n Describe
# **PLEASE UPVOTE \uD83D\uDC4D**\n# Approach \n### Simple implementation of stacks and because of circular array we take 2*n elements instead of n elements\n<!-- Describe your approach to solving the problem. -->\n\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\n# Code\n```\nclass Solution {\npublic:\n    vector<int> nextGreaterElements(vector<int>& a) {\n        int n = a.size();\n        vector<int>v(n,-1);\n\n        stack<int>st;\n        for(int i = 2*n - 1; i >= 0; i--)\n        {\n            // we pop out all elements smaller than current element\n            while(!st.empty() && (a[i%n] >= st.top()))\n            {\n                st.pop();\n            }\n\n            // if stack is empty means no greater element is there\n            // if not empty we make answer at that index equal to top element\n            if(!st.empty() && (i < n))\n            {\n                v[i] = st.top();\n            }\n\n            st.push(a[i%n]);\n        }\n\n        return v;\n    }\n};\n```\n\n![e2515d84-99cf-4499-80fb-fe458e1bbae2_1678932606.8004954.png](https://assets.leetcode.com/users/images/b1321a46-fa48-4dbb-aace-41f5c1cad2c6_1680879272.3589258.png)\n
['Stack', 'C++']