Next Greater Element
For a given array/list of integers of size N, print 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, which is greater than X. If no greater elements exist to the right of X, consider the next greater element as -1.
For example:
For the given array [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.
Output: [12, 20, 20, -1]
Input Format:
The first line of input contains an integer 'N' representing the size of the array/list.
The second line of input contains 'N' single space-separated integers representing the elements of the array/list.
Output Format :
The only line of output contains 'N' single space-separated integers representing the Next Greater Element for each element.
Note :
You do not need to print anything explicitly, it has already been taken care of.
Constraints :
1 <= N <= 10^5
1 <= ARR[i] <= 10^9
Time Limit: 1 sec
CodingNinjas
author
2y
Brute Force
For every element in the array, we will run a loop on its right side. As soon as we find an element on its right side which is greater than it, we will break the loop, assign it as the NGE ...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.
Here is the complete algorithm:
- Create a new array ANS[ ] of the same si...read more
Help your peers!
Add answer anonymously...
Top Groww Software Developer interview questions & answers
Popular interview questions of Software Developer
Top HR questions asked in Groww 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