For understanding the question, its variations and the possible solutions with detailed in depth explanation watch the video :
class NextGreaterChallenge {
public static int[] nextGreaterElement(int[] arr) {
int[] result = new int[arr.length];
int resultIndex = 0;
Stack<Integer> stack = new Stack<>(arr.length);
//Iterate over the array from last
for (int i = arr.length - 1; i >= 0; i--) {
//Pop all the elements which are smaller than current element
if (!stack.isEmpty()) {
while (!stack.isEmpty() && stack.top() <= arr[i]) {
stack.pop();
}
}
//if stack becomes empty, then NGE doesn't exit
if(stack.isEmpty()){
result[i] = -1;
}
//If stack is not empty, NGE is top of stack
else
result[i] = stack.top();
//Push current element into stack
stack.push(arr[i]);
}
return result;
}
}