> For the complete documentation index, see [llms.txt](https://ucan.gitbook.io/notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ucan.gitbook.io/notes/stack/503.-next-greater-element-ii.md).

# 503. Next Greater Element II

```java
class Solution {
    public int[] nextGreaterElements(int[] nums) {
        int[] result = new int[nums.length];
        
        // remember: Arrays.fill()
        Arrays.fill(result, -1);
        // store the index of num in nums
        Deque<Integer> stack = new LinkedList<>();
        // loop twice
        for(int i=0; i<nums.length*2; i++){
            // get the mod of i
            int index = i%nums.length;
            while(stack.size()>0 && nums[stack.peek()]<nums[index]){
                result[stack.pop()] = nums[index];
            }
            stack.push(index);
        }

        return result;
    }
}
```
