Next Greater Element
You have been given an array/list ‘ARR’ consisting of ‘N’ positive integers. Your task is to return the Next Greater Element(NGE) for every element.
The Next Greater Element for an element ‘X’ is the first element on the right side of ‘X’ in the array 'ARR', which is greater than ‘X’. If no such element exists to the right of ‘X’, then return -1.
For example:
For the given array 'ARR' = [7, 12, 1, 20]
The next greater element for 7 is 12.
The next greater element for 12 is 20.
The next greater element for 1 is 20.
There is no greater element for 20 on the right side.
So, the output is [12, 20, 20, -1].
Input Format:
The first line contains an Integer 'T' which denotes the number of test cases or queries to be run. Then the test cases follow.
The first line of each test case contains an integer 'N' representing the size of the array/list 'ARR'.
The second line of each test case contains 'N' single space-separated integers representing the elements of the given array/list ‘ARR’.
Output Format :
For each test case, print 'N' single space-separated integers representing the Next Greater Element for each element.
Note
You are not required to print anything, it has already been taken care of. Just implement the function.
Constraints :
1 <= T <= 100
1 <= N <= 5 * 10^3
1 <= ARR[i] <= 10^9
Time Limit: 1 sec
AnswerBot
1y
The task is to find the next greater element for each element in an array.
Iterate through the array from right to left
Use a stack to keep track of the elements
For each element, pop elements from the s...read more
CodingNinjas
author
2y
Brute Force
We will iterate through all the elements to their right and check if the element is greater than the current element. If we found the greater element, we will stop iteration for this elemen...read more
CodingNinjas
author
2y
Using Stack
We will use a Stack to keep track of the next greater element and pop as soon as we find an element greater than it.
The steps are as follows:
- Initialize an array ‘ANS’ of integer type and ...read more
Add answer anonymously...
Top Tata 1mg Software Developer interview questions & answers
Popular interview questions of Software Developer
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app