Using stack, two pass:
class Solution { public int[] nextGreaterElements(int[] nums) { Stack<Integer> stk = new Stack<>(); int[] res = new int[nums.length]; Arrays.fill(res, -1); stk.push(0); for(int i=1;i<nums.length;i++){ while(!stk.isEmpty() && nums[i]>nums[stk.peek()]){ res[stk.pop()]=nums[i]; } stk.push(i); } for(int i=0;i<nums.length;i++){ while(!stk.isEmpty() && nums[i]>nums[stk.peek()]){ res[stk.pop()]=nums[i]; } stk.push(i); } return res; } }