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)
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Smallest subset with sum greater than all other elements
- Smallest subarray such that all elements are greater than K
- Length of Smallest Subsequence such that sum of elements is greater than equal to K
- Smallest element greater than X not present in the array
- Find the smallest and second smallest elements in an array
- Merge first two minimum elements of the array until all the elements are greater than K
- 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
- Generate original array from an array that store the counts of greater elements on right
- Count elements in first Array with absolute difference greater than K with an element in second Array
- Find minimum value to assign all array elements so that array product becomes greater
- Find K such that changing all elements of the Array greater than K to K will make array sum N
- Count of elements in first Array greater than second Array with each element considered only once
- Length of longest subarray in which elements greater than K are more than elements not greater than K
- Count of greater elements for each element in the Array