503. Next Greater Element II

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;
    }
}

Last updated