![]() |
VOOZH | about |
3Given an array of distinct elements, print the closest greater element for every element. The closest greater element for an element x is the smallest element on the right side of x in array which is greater than x. Elements for which no greater element exist, consider next greater element as -1.
Examples:
Input: arr[] = {4, 5, 2, 25}
Output:
Element NGE
4 --> 5
5 --> 25
2 --> 25
25 --> -1
Input: arr[] = {4, 10, 7}
Output:
Element NGE
4 --> 7
10 --> -1
7 --> -1
Approach: In this post, we will be discussing how to find the Next Greater Element using C++ STL(set).
Finding the smallest greater element on the right side will be like finding the first greater element of the current element in a list that is sorted.
Consider example 1, The sorted list would look like 2, 4, 5, 25.
Here for element 4, the greater element is 5 as it is next to it, so we print 5 and remove 4 because it would not be greater to the other elements since it is no longer on anyone's right.
Similarly, for 5 it is 25 and we remove 5 from the list, as 5 will not be on the right side of 2 or 25, so it can be deleted.
Given below are the steps to find the Next Greater Element of every index element.
Implementation:
Element NGE 4 ----> 5 5 ----> 25 2 ----> 25 25 ----> -1
Complexity Analysis: