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

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 code
int main()
{
    int ar[] = { 6, 3, 9, 8, 10, 2, 1, 15, 7 };
    int n = sizeof(ar) / sizeof(ar[0]);
    smallestGreater(ar, n);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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 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)

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 code
int main()
{
    int ar[] = { 6, 3, 9, 8, 10, 2, 1, 15, 7 };
    int n = sizeof(ar) / sizeof(ar[0]);
    smallestGreater(ar, n);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 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 gauravrajput1

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Efficient Python3 program to
# find smallest greater element
# in whole array for every element
def 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 code
if __name__ == '__main__':
     
    ar = [ 6, 3, 9, 8, 10, 2, 1, 15, 7 ]
    n = len(ar)
     
    smallestGreater(ar, n)
 
# This code is contributed by shikhasingrajput

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 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 29AjayKumar

chevron_right


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.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Recommended Posts:


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.