Challenge: Next Greater Element Using a Stack

Using a stack, can you implement a function to find the next greater element after any given element in an array?

Problem Statement #

You must implement the nextGreaterElement() function. 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.

Input #

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.