Smallest greater elements in whole array

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.

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

Recommended: Please solve it on “PRACTICE” first, before moving on to the solution.

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.

C++

 // Simple CPP program to find smallest // greater element in whole array for  // every element. #include using namespace std;    void smallestGreater(int arr[], int n) {     for (int i = 0; i < n; i++) {            // Find the closest greater element          // for arr[j] in the entire array.         int diff = INT_MAX, closest = -1;         for (int j = 0; j < n; j++) {             if ( arr[i] < arr[j] &&                   arr[j] - arr[i] < diff)             {                 diff = arr[j] - arr[i];                 closest = j;                         }         }                    // Check if arr[i] is largest         (closest == -1)?  cout << "_ "  :                cout << arr[closest] << " ";      } }    // Driver code int main() {     int ar[] = { 6, 3, 9, 8, 10, 2, 1, 15, 7 };     int n = sizeof(ar) / sizeof(ar);     smallestGreater(ar, n);     return 0; }

Java

 // Simple Java program to find // smallest greater element in  // whole array for every element. import java.io.*;    class GFG  { static void smallestGreater(int arr[],                              int n) {     for (int i = 0; i < n; i++)      {            // Find the closest greater         // element for arr[j] in          // the entire array.         int diff = Integer.MAX_VALUE;         int closest = -1;         for (int j = 0; j < n; j++)          {             if (arr[i] < arr[j] &&                  arr[j] - arr[i] < diff)             {                 diff = arr[j] - arr[i];                 closest = j;                      }         }                    // Check if arr[i] is largest         if(closest == -1)         System.out.print( "_ " );         else         System.out.print(arr[closest] + " ");     } }    // Driver code public static void main (String[] args)  {     int ar[] = {6, 3, 9, 8, 10,                  2, 1, 15, 7};     int n = ar.length;     smallestGreater(ar, n); } }    // This code is contributed by anuj_67.

Python3

 # Simple Python program to find smallest # greater element in whole array for  # every element. def smallestGreater(arr, n) :     for i in range(0, n) :            # Find the closest greater element          # for arr[j] in the entire array.         diff = 1000;          closest = -1;         for j in range(0, n) :             if ( arr[i] < arr[j] and                    arr[j] - arr[i] < diff) :                 diff = arr[j] - arr[i];                 closest = j;                         # Check if arr[i] is largest         if (closest == -1) :             print ("_ ", end = "");         else :             print ("{} ".format(arr[closest]),                                     end = "");    # Driver code ar = [6, 3, 9, 8, 10, 2, 1, 15, 7]; n = len(ar) ; smallestGreater(ar, n);    # This code is contributed by Manish Shaw # (manishshaw1)

C#

 // Simple C# program to find // smallest greater element in  // whole array for every element. using System;    class GFG  { static void smallestGreater(int []arr,                              int n) {     for (int i = 0; i < n; i++)      {            // Find the closest greater         // element for arr[j] in          // the entire array.         int diff = int.MaxValue;         int closest = -1;         for (int j = 0; j < n; j++)          {             if (arr[i] < arr[j] &&                  arr[j] - arr[i] < diff)             {                 diff = arr[j] - arr[i];                 closest = j;                      }         }                    // Check if arr[i] is largest         if(closest == -1)         Console.Write( "_ " );         else         Console.Write(arr[closest] + " ");     } }    // Driver code public static void Main()  {     int []ar = {6, 3, 9, 8, 10,                  2, 1, 15, 7};     int n = ar.Length;     smallestGreater(ar, n); } }    // This code is contributed by anuj_67.

PHP



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 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.

C++

 // Efficient CPP program to find smallest // greater element in whole array for  // every element. #include using namespace std;    void smallestGreater(int arr[], int n) {     set s;     for (int i = 0; i < n; i++)         s.insert(arr[i]);        for (int i = 0; i < n; i++)      {        auto it = s.find(arr[i]);        it++;        if (it != s.end())                      cout << *it << " ";               else           cout << "_ ";      } }    // Driver code int main() {     int ar[] = { 6, 3, 9, 8, 10, 2, 1, 15, 7 };     int n = sizeof(ar) / sizeof(ar);     smallestGreater(ar, n);     return 0; }

Output :

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)

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

My Personal Notes arrow_drop_up Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. 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.

Improved By : jit_t, vt_m, manishshaw1