JAVA SOLUTION✅✅ || STEP BY STEP EXPLAINED🤗
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time 
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->O(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->O(N)\n![Screenshot_20230205_171246.png](https://assets.leetcode.com/users/images/7b4f2f22-6f9b-40cb-b7ab-d1a4cb42459d_1682789828.16653.png)\n\n\n# Code\n```\nclass Solution {\n    public int[] nextGreaterElements(int[] nums) {\n        \n        int n = nums.length;\n        Stack<Integer> st = new Stack<>(); // create a stack to store indices of elements\n\n        // first loop to find the next greater element for each element in nums (except the last one)\n        for(int i = n-2; i >= 0; i--){\n\n            // while the stack is not empty and the top element is smaller than or equal to the current element in nums\n            while(st.size() > 0 && st.peek() <= nums[i]){\n                st.pop(); // remove the top element from stack\n            }\n            st.push(nums[i]); // push the current element in nums into stack\n        }\n\n        int ans[] = new int[nums.length];\n\n        // second loop to find the next greater element for the remaining elements (including the last one)\n        for(int i = n-1; i >= 0; i--){\n\n            // while the stack is not empty and the top element is smaller than or equal to the current element in nums\n            while(st.size() > 0 && nums[i] >= st.peek()){\n                st.pop(); // remove the top element from stack\n            }\n            \n            if(st.size() == 0){\n                ans[i] = -1; // if stack is empty, set the answer to -1 (no next greater element found)\n            }else{\n                ans[i] = st.peek(); // otherwise, set the answer to the top element of the stack\n            }\n\n            st.push(nums[i]); // push the current element in nums into stack\n        }\n        return ans; // return the answer array\n    }\n}\n\n```
['Array', 'Stack', 'Java']