Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Next Greater Element

Moderate
0/80
Average time to solve is 20m
profile
Contributed by
145 upvotes
Asked in companies
SamsungDunzoCIS - Cyber Infrastructure

Problem statement

You are given an array arr of length N. You have to return a list of integers containing the NGE(next greater element) of each element of the given array. The 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 exists, consider the NGE as -1.

For Example :

If the given array is [1, 3, 2], then you need to return [3, -1, -1]. Because for 1, 3 is the next greater element, for 3 it does not have any greater number to its right, and similarly for 2.
Detailed explanation ( Input/output format, Notes, Images )
Constraints :
1 <= T <= 10
1 <= N <= 10^5
0 <= ARR[i] <= 10^9

Time Limit: 1sec
Sample Input 1 :
1
4
1 2 4 3
Sample Output 1 :
2 4 -1 -1
Sample Input 2 :
1
4
9 3 6 5
Sample Output 2 :
-1 6 -1 -1
Explanation for Sample Input 2 :
For element 9, there is no next greater element. So -1 would be the next greater element.
For element 3, 6 is the next greater element. 
For element 6, there is no next greater element. So -1 would be the next greater element.
For element 5, there is no next greater element. So -1 would be the next greater element.
Full screen
Console