VOOZH about

URL: https://www.geeksforgeeks.org/dsa/smallest-greater-elements-in-whole-array/

⇱ Smallest greater elements in whole array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Smallest greater elements in whole array

Last Updated : 11 Jul, 2025

An array is given of n length, and we need to calculate the next greater element for each element in the given array. If the next greater element is not available in the given array then we need to fill '_' at that index place.

Examples : 

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 the inner loop finds the next greater element by linearly searching from beginning to end. 


Output: 
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 it into the set, we search elements. After we find the iterator of the searched element, we move the iterator to next (note that set stores elements in sorted order) to find an element that is just greater.


Output : 
7 6 10 9 15 3 2 _ 8

 

Time Complexity: O(n Log n). Note that the self-balancing search tree (implemented by set in C++) insert operations take O(Log n) time to insert and find. 
Auxiliary Space: O(n)

We can also use sorting followed by binary searches to solve the above problem at the same time and the same auxiliary space.

Comment
Article Tags:
Article Tags: