✅ Easy and Optimal Solution || TC : O(N) || SC: O(N) ||
Prerequisite\n\nThis problem is similar to Find next greater element-1.\n# Approach\n Describe your approach to solving the problem. \n- Finding next greater el
# Prerequisite\n\nThis problem is similar to [Find next greater element-1](https://leetcode.com/problems/next-greater-element-i/description/).\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Finding next greater element in an array is similar to this problem.\n- The only change here is the next greater elements can be found in circular fashion too from end to starting of array.\n- So for elements at end of array, we can look at startin of array for it\'s nge. SO BASICALLY THIS IS A CIRCULAR ARRAY.\n- Notice one thing, *if we just append this array to end of this array, this problem can be solved directly using nge approach*.\n\n- So repeat the same process except keep in mind the indices we need for result.\n\n# Code\n```\nclass Solution {\npublic:\n    vector<int> nextGreaterElements(vector<int>& nums) {\n        int n=nums.size();\n        vector<int> res(n,-1);\n        stack<int> st;\n        //assume appending nums to it again but it can be done using index manipulation without actually appending\n        for(int i=2*n-1;i>=0;--i){\n            while(!st.empty() and st.top()<=nums[i%n]) st.pop();//remove all smaller elements\n            if(i<n){\n                if(!st.empty()) res[i]=st.top();\n            }\n            st.push(nums[i%n]);\n        }\n        return res;\n    }\n};\n```
['Stack', 'Monotonic Stack', 'C++']