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.
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
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem