C++ | Stack | Explained | O(2*n)
Imagine the input array as a concatenation of the same array, twice. [1,2,1] -> [1,2,1,1,2,1]\n Similar to Next Greater Element, store the index in the stack in
* Imagine the input array as a concatenation of the same array, *twice*. ```[1,2,1] -> [1,2,1,1,2,1]```\n* Similar to *Next Greater Element*, store the ***index*** in the stack instead of the actual value.\n\n```\nclass Solution {\npublic:\n    vector<int> nextGreaterElements(vector<int>& nums) \n    {\n        int n = nums.size();\n        nums.resize(2*n);\n        \n        for(int i=n; i<2*n; i++) //concatenate the same array\n        {\n            nums[i] = nums[i-n];\n        }\n        \n        vector<int> res(n, -1); //to be returned, initialize it with -1\n        stack<int> st;\n        \n        for(int i=0; i<2*n; i++)\n        {\n            int ele = nums[i];\n            \n            while(!st.empty() && ele > nums[st.top()])\n            {\n\t\t\t\t//ele acts as NGE to the value at st.top()\n\t\t\t\t\n                if(st.top() >= n) //index should not exceed n\n                {\n                    st.top() = st.top() - n;\n                }\n                \n                res[st.top()] = ele;\n                st.pop();\n            }\n            \n            st.push(i);\n        }\n        \n        return res;\n    }\n};\n\n```\n\n**Upvote if this helped**
['Stack', 'C', 'C++']