Challenge 7: 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 int [] nextGreaterElement(int [] arr, int size) 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, you should only check the array elements appearing after the current element.

Input

An integer array and its size is the input.

Output

The output is an array containing the next greater element of each element from the input list. For the maximum value in the list, the next greater value is -1.

Sample input

int 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.