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 a list?
We'll cover the following
Problem Statement
You are required to implement the next_greater_element()
function. For each element in a list, the function finds the first element to its right which is greater than element . If for any element such a value does not exist, the answer is -1
.
Note: The next greater element is the first element towards the right which is greater than the given element. For example, in the list [1, 3, 8, 4, 10, 5], the next greater element of 3 is 8 and the next greater element for 8 is 10.
Input
An integer list.
Output
A list containing the next greater element of each element from the input list.
Sample Input
list = [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.