An array is given of n length, and we need to calculate the next greater element for each element in given array. If next greater element is not available in given array then we need to fill ‘_’ at that index place.
Input : 6 3 9 8 10 2 1 15 7 Output : 7 6 10 9 15 3 2 _ 8 Here every element of array has next greater element but at index 7, 15 is the greatest element of given array and no other element is greater from 15 so at the index of 15 we fill with '_' . Input : 13 6 7 12 Output : _ 7 12 13 Here, at index 0, 13 is the greatest value in given array and no other array element is greater from 13 so at index 0 we fill '_'.
Asked in : Zoho
A simple solution is to use two loops nested. The outer loop picks all elements one by one and inner loop finds the next greater element by linearly searching from beginning to end.
7 6 10 9 15 3 2 _ 8
Time Complexity : O(n*n)
Auxiliary Space: O(1)
An efficient solution is to one by one insert elements in a set (A self balancing binary search tree). After inserting into set, we search elements. After we find iterator of the searched element, we move iterator to next (note that set stores elements in sorted order) to find element which is just greater.
7 6 10 9 15 3 2 _ 8
Time Complexity : O(n Log n). Note that self balancing search tree (implemented by set in C++) insert operations take O(Log n) time to insert and find.
Auxiliary Space: O(n)
- Smallest subset with sum greater than all other elements
- Smallest subarray such that all elements are greater than K
- Smallest element greater than X not present in the array
- Find the smallest and second smallest elements in an array
- Average of remaining elements after removing K largest and K smallest elements from array
- Find all elements in array which have at-least two greater elements
- Find minimum value to assign all array elements so that array product becomes greater
- Generate original array from an array that store the counts of greater elements on right
- Length of longest subarray in which elements greater than K are more than elements not greater than K
- Elements greater than the previous and next element in an Array
- Adding elements of an array until every element becomes greater than or equal to k
- Find the number of elements greater than k in a sorted array
- Sum of elements in an array with frequencies greater than or equal to that element
- Number of ways to choose an integer such that there are exactly K elements greater than it in the given array
- Count the number of elements which are greater than any of element on right side of an array
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.