Smallest greater elements in whole array
Last Updated :
29 Mar, 2024
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++
// 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;
}
// This code is contributed by Aditya Kumar (adityakumar129)
C
// 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 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;
}
// This code is contributed by Aditya Kumar (adityakumar129)
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 Aditya Kumar (adityakumar129)
Python3
# 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)
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
<?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
?>
JavaScript
<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>
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++
// 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;
}
Java
// 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
Python3
# 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
C#
// 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
JavaScript
<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 code
let ar=[6, 3, 9, 8,
10, 2, 1, 15, 7];
let n = ar.length;
smallestGreater(ar, n);
// This code is contributed by patel2127
</script>
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.
Similar Reads
Find k smallest elements in an array Given an array arr[] and an integer k, the task is to find k smallest elements in the given array. Elements in the output array can be in any order.Examples:Input: arr[] = [1, 23, 12, 9, 30, 2, 50], k = 3Output: [1, 2, 9]Input: arr[] = [11, 5, 12, 9, 44, 17, 2], k = 2Output: [2, 5]Table of Content[A
15 min read
Least frequent element in an array Given an array, find the least frequent element in it. If there are multiple elements that appear least number of times, print any one of them. Examples : Input : arr[] = {1, 3, 2, 1, 2, 2, 3, 1}Output : 3Explanation: 3 appears minimum number of times in given array. Input : arr[] = {10, 20, 30}Outp
11 min read
Find closest smaller value for every element in array Given an array of integers, find the closest smaller element for every element. If there is no smaller element then print -1 Examples: Input : arr[] = {10, 5, 11, 6, 20, 12} Output : 6, -1, 10, 5, 12, 11 Input : arr[] = {10, 5, 11, 10, 20, 12} Output : 5 -1 10 5 12 11 A simple solution is to run two
4 min read
Print n smallest elements from given array in their original order We are given an array of m-elements, we need to find n smallest elements from the array but they must be in the same order as they are in given array. Examples: Input : arr[] = {4, 2, 6, 1, 5}, n = 3 Output : 4 2 1 Explanation : 1, 2 and 4 are 3 smallest numbers and 4 2 1 is their order in given arr
5 min read
Floor of every element in same array Given an array of integers, find the closest smaller or same element for every element. If all elements are greater for an element, then print -1. We may assume that the array has at least two elements. Examples: Input : arr[] = {10, 5, 11, 10, 20, 12} Output : 10 -1 10 10 12 11 Note that there are
14 min read