Challenge: Next Greater Element Using Stack

Can you implement a method to find the next greater element after any given element from the stack? A solution is placed in the "solution" section to help you, but we would suggest you try to solve it on your own first.

Problem Statement #

In this problem, you have to implement int[] nextGreaterElement(int[] arr) method. For each element in an array, it finds the next greater element in that array.

Note: The next greater element is the first element towards the right, which is greater than the current element. For example, in the array [1, 3, 8, 4, 10, 5], the next greater element of 3 is 8, and the next greater element for 8 is 10. To keep it simple, the next greater element for the last or maximum value in the array is -1.

In each iteration, we only check the array elements appearing after the current element.

Method Prototype #

int[] nextGreaterElement(int[] arr);

where arr is an Integer array

Input #

The input is an integer array

Output #

An array containing the next greater element of each element from the input array. For the maximum value in the array, the next greater value is -1.

Sample Input #

arr = {4,6,3,2,8,1}

Sample Output #

result = {6,8,8,8,-1,-1}

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.