Easy C++ Solution | Step-wise Approach Explained | Beats 92.38% | Stacks
Intuition and Approach\n Describe your first thoughts on how to solve this problem. \nImagine a scenario where you have a circular arrangement of numbers, like 
# Intuition and Approach\n<!-- Describe your first thoughts on how to solve this problem. -->\nImagine a scenario where you have a **circular arrangement** of numbers, like a loop, and for each number, you want to find the next greater number in the loop. The catch is that the loop wraps around, meaning the next greater element for the last number might be at the beginning of the loop.\n\nWe can use a $$stack$$ to keep track of potential candidates for the next greater element. We traverse the **circular array** twice to ensure that we consider elements in a circular manner. For each element:\n\n1) If the stack is not empty and the current element is greater than the element at the top of the stack, we **update** the $$result$$ for the top element.\n2) Push the current element onto the stack.\n3) After the two passes, the result array contains the next greater element for each element in the circular array. Two passes are considered here, because we are interested to know from double sized array (in order to make sure there is a greater element previously in array which can be accessed further).\n\n--------------------------------------------------------------------\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---------------------------------------------------------------------\n**If you find this solution helpful, consider giving it an upvote!**\n\n----------------------------------------------------------------------\n\n#### Do check out all other solutions posted by me here: https://github.com/adityajamwal02/Leetcode-Community-Solutions\n\n-------------------------------------------------------------------\n\n# Code\n```\nclass Solution {\npublic:\n    vector<int> nextGreaterElements(vector<int>& nums) {\n        int n=nums.size();\n        vector<int> result(n,-1);\n        stack<int> st;\n        for(int i=2*n-1;i>=0;i--){          // Circular array (double size)\n            while(!st.empty() and st.top()<=nums[i%n]){\n                st.pop();\n            }\n            if(i<n){\n                if(!st.empty()) result[i]=st.top();\n            }\n        st.push(nums[i%n]);\n        }\n    return result;        \n    }\n};\n```
['Array', 'Stack', 'C++']