EASY BEGINNER|| JAVA C++ PYTHON || STEPWISE
THE QUESTION IS SAME AS "THE NEXTGREATER ELEMENT" ON LEETCODE , I WILL RECOMMEND YOU TO TRY THAT FIRST THEN THIS IS GOING TO BE A CAKEWALK. AS CLICHE AS IT SOUN
# THE QUESTION IS SAME AS "THE NEXTGREATER ELEMENT" ON LEETCODE , I WILL RECOMMEND YOU TO TRY THAT FIRST THEN THIS IS GOING TO BE A CAKEWALK. AS CLICHE AS IT SOUNDS , SERIOUSLY.\n\n**1. Stack Initialization:**\n   - A stack `st` is created to store elements in decreasing order.\n\n**2. Iterating Through the Array Twice:**\n   - The code iterates through the array twice, effectively treating it as a circular array.\n   - For each element `nums[i]`:\n     - While the stack is not empty and the top element is less than or equal to the current element, pop elements from the stack.\n     - If the stack is empty, it means there\'s no greater element to the right of the current element, so -1 is assigned to the corresponding index in the `ans` array.\n     - Otherwise, the top element of the stack is the next greater element, so it\'s assigned to the corresponding index in the `ans` array.\n     - The current element is pushed onto the stack.\n\n**3. Return Result:**\n   - The `ans` array containing the next greater elements for each element in the circular array is returned.\n\n\n\n\n# Code\n```java []\nclass Solution {\n    public int[] nextGreaterElements(int[] nums) {\n        int [] ans=new int[nums.length];\n        Stack<Integer> st=new Stack<>();\n        for(int i=nums.length*2-2;i>=0;i--){\n            while(!st.isEmpty() && st.peek()<=nums[i%nums.length]){\n                st.pop();\n            }\n            if(st.isEmpty()) ans[i%nums.length]=-1;\n            else ans[i%nums.length]=st.peek();\n            st.push(nums[i%nums.length]);\n        }\n        return ans;\n    }\n}\n```\n```C++ []\n#include <vector>\n#include <stack>\nusing namespace std;\n\nclass Solution {\npublic:\n    vector<int> nextGreaterElements(vector<int>& nums) {\n        int n = nums.size();\n        vector<int> ans(n, -1);\n        stack<int> st;\n\n        for(int i = 2 * n - 2; i >= 0; i--) {\n            while(!st.empty() && st.top() <= nums[i % n]) {\n                st.pop();\n            }\n            if(!st.empty()) {\n                ans[i % n] = st.top();\n            }\n            st.push(nums[i % n]);\n        }\n\n        return ans;\n    }\n};\n```\n```python []\nfrom typing import List\n\nclass Solution:\n    def nextGreaterElements(self, nums: List[int]) -> List[int]:\n        n = len(nums)\n        ans = [-1] * n\n        st = []\n\n        for i in range(2 * n - 2, -1, -1):\n            while st and st[-1] <= nums[i % n]:\n                st.pop()\n            if st:\n                ans[i % n] = st[-1]\n            st.append(nums[i % n])\n\n        return ans\n```\n\n
['Stack', 'Python', 'C++', 'Java']