Smallest greater elements in whole array

Difficulty Level :
Medium
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. 
C++
C
Java
Python3
C#
PHP
Javascript
// Simple C++ program to find smallest greater element in// whole array for every element.#include <bits/stdc++.h>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 codeint main(){    int ar[] = { 6, 3, 9, 8, 10, 2, 1, 15, 7 };    int n = sizeof(ar) / sizeof(ar[0]);    smallestGreater(ar, n);    return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// Simple C program to find smallest greater element in// whole array for every element.#include <stdio.h>#include <limits.h> 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) ? printf("_ ")                        : printf("%d ",arr[closest]);    }} // Driver codeint main(){    int ar[] = { 6, 3, 9, 8, 10, 2, 1, 15, 7 };    int n = sizeof(ar) / sizeof(ar[0]);    smallestGreater(ar, n);    return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// 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 Aditya Kumar (adityakumar129)
# Simple Python3 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 codear = [6, 3, 9, 8, 10, 2, 1, 15, 7];n = len(ar) ;smallestGreater(ar, n); # This code is contributed by Manish Shaw# (manishshaw1)
// 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 codepublic 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// Simple PHP program to find smallest// greater element in whole array for// every element. function smallestGreater($arr, $n){    for ( $i = 0; $i < $n; $i++) {         // Find the closest greater element        // for arr[j] in the entire array.        $diff = PHP_INT_MAX; $closest = -1;        for ( $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)        echo "_ " ;        else            echo $arr[$closest] , " ";    }}     // Driver code    $ar = array (6, 3, 9, 8, 10, 2, 1, 15, 7);    $n = sizeof($ar) ;    smallestGreater($ar, $n); // This code is contributed by ajit?>
<script>     // Simple Javascript program to find    // smallest greater element in    // whole array for every element.         function smallestGreater(arr, n)    {        for (let i = 0; i < n; i++)        {             // Find the closest greater            // element for arr[j] in            // the entire array.            let diff = Number.MAX_VALUE;            let closest = -1;            for (let 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)                document.write( "_ " );            else                document.write(arr[closest] + " ");        }    }         let ar = [6, 3, 9, 8, 10, 2, 1, 15, 7];    let n = ar.length;    smallestGreater(ar, n);     </script>
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.
C++
Java
Python3
C#
Javascript
// Efficient C++ program to find smallest// greater element in whole array for// every element.#include <bits/stdc++.h>using namespace std; void smallestGreater(int arr[], int n){    set<int> 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 codeint main(){    int ar[] = { 6, 3, 9, 8, 10, 2, 1, 15, 7 };    int n = sizeof(ar) / sizeof(ar[0]);    smallestGreater(ar, n);    return 0;}
// Efficient Java program to// find smallest greater element// in whole array for every element.import java.util.*;class GFG{ static void smallestGreater(int arr[],                            int n){  HashSet<Integer> s = new HashSet<>();  for (int i = 0; i < n; i++)    s.add(arr[i]);  Vector<Integer> newAr = new Vector<>();  for (int p : s)  {    newAr.add(p);  }   for (int i = 0; i < n; i++)  {    int temp = lowerBound(newAr, 0,                          newAr.size(),                          arr[i]);    if (temp  < n)      System.out.print(newAr.get(temp) + " ");    else      System.out.print("_ ");  }} static int lowerBound(Vector<Integer> vec,                      int low, int high,                      int element){  int[] array = new int[vec.size()];  int k = 0;  for (Integer val : vec)  {    array[k] = val;    k++;  }     // vec.clear();  while (low < high)  {    int middle = low +                 (high - low) / 2;    if (element > array[middle])    {      low = middle + 1;    } else    {      high = middle;    }  }   return low+1;} // Driver codepublic 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 gauravrajput1
# Efficient Python3 program to# find smallest greater element# in whole array for every elementdef smallestGreater(arr, n):         s = set()         for i in range(n):        s.add(arr[i])             newAr = []         for p in s:        newAr.append(p)     for i in range(n):        temp = lowerBound(newAr, 0, len(newAr),                          arr[i])                                   if (temp < n):            print(newAr[temp], end = " ")        else:            print("_ ", end = "") def lowerBound(vec, low, high, element):         array = [0] * (len(vec))         k = 0         for val in vec:        array[k] = val        k += 1             # vec.clear();    while (low < high):        middle = low + int((high - low) / 2)                 if (element > array[middle]):            low = middle + 1        else:            high = middle     return low + 1 # Driver codeif __name__ == '__main__':         ar = [ 6, 3, 9, 8, 10, 2, 1, 15, 7 ]    n = len(ar)         smallestGreater(ar, n) # This code is contributed by shikhasingrajput
// Efficient C# program to// find smallest greater element// in whole array for every element.using System;using System.Collections.Generic;class GFG{ static void smallestGreater(int[] arr,                                int n){  HashSet<int> s = new HashSet<int>();  for (int i = 0; i < n; i++)  {    s.Add(arr[i]);  }     int[] newAr = new int[s.Count];  int j = 0;  foreach(int p in s)  {    newAr[j] = p;    j++;  }     Array.Sort(newAr);     for (int i = 0; i < n; i++)  {    int temp = lowerBound(newAr, 0,                          newAr.GetLength(0),                          arr[i]);    if (temp < n)      Console.Write(newAr[temp] + " ");    else      Console.Write("_ ");  }} static int lowerBound(int[] array, int low,                      int high, int element){  while (low < high)  {    int middle = low + (high -                 low) / 2;         if (element > array[middle])    {      low = middle + 1;    }    else    {      high = middle;    }  }  return low + 1;} // Driver codepublic 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 29AjayKumar
<script>// Efficient Javascript program to// find smallest greater element// in whole array for every element. function smallestGreater(arr,n){     let s = new Set();  for (let i = 0; i < n; i++)    s.add(arr[i]);  let newAr = [];  for (let p of s.values())  {    newAr.push(p);  }     newAr.sort(function(a,b){return a-b;});       for (let i = 0; i < n; i++)  {           let temp = lowerBound(newAr, 0,                          newAr.length,                          arr[i]);         if(temp  < n)      document.write(newAr[temp] + " ");    else      document.write("_ ");  }} function lowerBound(vec,low,high,element){    let array = [...vec];         // vec.clear();  while (low < high)  {    let middle = Math.floor(low +                 (high - low) / 2);    if (element > array[middle])    {      low = middle + 1;    }    else    {      high = middle;    }  }    return low+1;} // Driver codelet ar=[6, 3, 9, 8,              10, 2, 1, 15, 7];let n = ar.length;smallestGreater(ar, n); // This code is contributed by patel2127</script>
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.
jit_t
vt_m
manishshaw1
GauravRajput1
29AjayKumar
shikhasingrajput
mukesh07
patel2127
adityakumar129
cpp-set
STL
Zoho
Arrays
Searching
Sorting
Zoho
Arrays
Searching
Sorting
STL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.