✅ C++ | 2 Stacks and 1 stack Approach | 98% Faster | Linear Time
503. Next Greater Element II\n\n1. Using Two Stacks :\nTime Complexity : O(n)\nSpace Complexity : O(2*n)\n\n\nvector<int> nextGreaterElements(vector<int>& nums)
[**503. Next Greater Element II**](https://leetcode.com/problems/next-greater-element-ii/)\n\n**1. Using Two Stacks :**\n**`Time Complexity : O(n)`**\n**`Space Complexity : O(2*n)`**\n\n```\nvector<int> nextGreaterElements(vector<int>& nums) {\n        stack<int>st1, st2;\n        for(int i=nums.size()-1; i>=0; i--)st1.push(nums[i]);\n        vector<int>ans(nums.size(), -1);\n        for(int i=nums.size()-1; i>=0; i--){\n            bool flag=false;\n            while(!st2.empty()){\n                if(st2.top()>nums[i]){\n                    ans[i]=st2.top();\n                    flag=true;\n                    break;\n                }\n                st2.pop();\n            }\n            while(!flag and !st1.empty()){\n                if(st1.top()>nums[i]){\n                    ans[i]=st1.top();\n                    flag=true;\n                    break;\n                }\n                st1.pop();\n            }\n            st2.push(nums[i]);\n        }\n        return ans;\n    }\n```\n**2. Using One Stack :**\n**`Time Complexity : O(n)`**\n**`Space Complexity : O(n)`**\n\n```\nvector<int> nextGreaterElements(vector<int>& nums) {\n        stack<int>st;\n        int n=nums.size();\n        vector<int>ans(n, -1);\n        for(int i=0; i<2*n-1; i++){\n            while(!st.empty() and nums[st.top()]<nums[i%n]){\n                ans[st.top()]=nums[i%n];\n                st.pop();\n            }\n            st.push(i%n);\n        }\n        return ans;\n    }\n```\n***Happy Coding :)***\n```\nif(liked(\u2764\uFE0F)==true) Upvote(\u2B06\uFE0F);\nelse Comment(\uD83D\uDCDD);\nreturn Thank You\uD83D\uDE01;\n```\n![image](https://assets.leetcode.com/users/images/72ce6908-d90b-4027-a43e-d942c1f5f8c6_1665044202.957393.png)\n
['Stack', 'C']