Find closest greater value for every element in array - GeeksforGeeks

04 May, 2022
Given an array of integers, find the closest greater element for every element. If there is no greater element then print -1Examples:  
Input : arr[] = {10, 5, 11, 6, 20, 12} Output : 11 6 12 10 -1 20Input : arr[] = {10, 5, 11, 10, 20, 12} Output : 11 10 12 11 -1 20  
 
A simple solution is to run two nested loops. We pick an outer element one by one. For every picked element, we traverse remaining array and find closest greater element. Time complexity of this solution is O(n*n)A better solution is to use sorting. We sort all elements, then for every element, traverse toward right until we find a greater element (Note that there can be multiple occurrences of an element).An efficient solution is to use Self Balancing BST (Implemented as set in C++ and TreeSet in Java). In a Self Balancing BST, we can do both insert and closest greater operations in O(Log n) time. 
C++
Java
Python3
C#
Javascript
// C++ program to find closest greater value// for every array element#include <bits/stdc++.h>using namespace std; void closetGreater(int arr[], int n){    // Insert all array elements into a Set    set<int> ts;    for (int i = 0; i < n; i++)        ts.insert(arr[i]);     // Find smallest greater element for    // every array element    for (int i = 0; i < n; i++)    {        auto greater = ts.upper_bound(arr[i]);         if (greater == ts.end())            cout << -1 << " ";        else            cout << *greater << " ";    }} // Driver codeint main(int argc, char const *argv[]){    int arr[] = {10, 5, 11, 10, 20, 12};    int n = sizeof(arr) / sizeof(arr[0]);    closetGreater(arr, n);    return 0;} // This code is contributed by// sanjeev2552
// Java program to find closest greater value for// every array elementimport java.util.*; class TreeSetDemo {    public static void closestGreater(int[] arr)    {        // Insert all array elements into a TreeSet        TreeSet<Integer> ts = new TreeSet<Integer>();        for (int i = 0; i < arr.length; i++)            ts.add(arr[i]);         // Find smallest greater element for every        // array element        for (int i = 0; i < arr.length; i++) {            Integer greater = ts.higher(arr[i]);            if (greater == null)                System.out.print(-1 + " ");            else                System.out.print(greater + " ");        }    }     public static void main(String[] args)    {        int[] arr = { 10, 5, 11, 10, 20, 12};        closestGreater(arr);    }}
# Python program to find closest greater value# for every array elementdef upper_bound(s, val):    temp = list(s).copy()    temp.sort()    try:        index_value = temp.index(val)        if(index_value == len(temp)-1):            return 0        return temp[index_value+1]    except ValueError:        return arr[0] def closetGreater(arr, n):    # Insert all array elements into a Set    ts = set()    for i in range(n):        ts.add(arr[i])     # Find smallest greater element for    # every array element    for i in range(n):        greater = upper_bound(ts, arr[i])         if (greater == 0):            print(-1,end = " ")        else:            print(greater,end = " ")     # Driver codearr = [10, 5, 11, 10, 20, 12]n = len(arr)closetGreater(arr, n)  # This code is contributed by shinjanpatra
// C# program to find closest greater value for// every array elementusing System;using System.Collections.Generic; public class TreeSetDemo {  public static void closestGreater(int[] arr)  {         // Insert all array elements into a TreeSet    SortedSet<int> ts = new SortedSet<int>();    for (int i = 0; i < arr.Length; i++)      ts.Add(arr[i]);     // Find smallest greater element for every    // array element    for (int i = 0; i < arr.Length; i++) {      int greater = upper_bound(ts, arr[i]);      if (greater == -1)        Console.Write(-1 + " ");      else        Console.Write(greater + " ");    }  }  public static int upper_bound(SortedSet<int> s, int val)  {    List<int> temp = new List<int>();    temp.AddRange(s);    temp.Sort();    if (temp.IndexOf(val) + 1 == temp.Count)      return -1;    else      return temp[temp.IndexOf(val) + 1];  }  public static void Main(String[] args)  {    int[] arr = { 10, 5, 11, 10, 20, 12 };    closestGreater(arr);  }} // This code is contributed by Rajput-Ji
<script> // JavaScript program to find closest greater value// for every array element function closetGreater(arr, n) {    // Insert all array elements into a Set    let ts = new Set();    for (let i = 0; i < n; i++)        ts.add(arr[i]);     // Find smallest greater element for    // every array element    for (let i = 0; i < n; i++) {        let greater = upper_bound(ts, arr[i]);         if (!greater)            document.write(-1 + " ");        else            document.write(greater + " ");    }} function upper_bound(s, val) {    let temp = [...s];    temp.sort((a, b) => a - b);    return temp[temp.indexOf(val) + 1];} // Driver code let arr = [10, 5, 11, 10, 20, 12];let n = arr.length;closetGreater(arr, n);  // This code is contributed by _saurabh_jaiswal </script>
11 10 12 11 -1 20
 
Time Complexity : O(n Log n) 
sanjeev2552
_saurabh_jaiswal
Rajput-Ji
shinjanpatra
java-treeset
Self-Balancing-BST
Arrays
Binary Search Tree
Arrays
Binary Search Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count pairs with given sum
Chocolate Distribution Problem
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
Binary Search Tree | Set 1 (Search and Insertion)
AVL Tree | Set 1 (Insertion)
Binary Search Tree | Set 2 (Delete)
A program to check if a binary tree is BST or not
Construct BST from given preorder traversal | Set 1