Next Greater Element in Stacks and Queues
Next Greater Element in Stacks and Queues
Given an array, find the next greater element for each element in the array.
The Next Greater Element (NGE) for an element x is the first greater
element on the right side of x in the array. Elements for which no greater
element exist, the NGE is considered as -1.
A = [4, 5, 2, 25]
NGE for 4 is 5
NGE for 5 is 25
NGE for 2 is 25
NGE for 25 is -1
Explanation:
The brute force way to solve this is by using two nested loops, checking each
element against every other element that follows it to find the NGE, which
leads to an O(n^2) time complexity.
https://www.codechef.com/learn/course/stacks-and-queues/LSTACKS02/problems/STACK13 1/1