Open In App

Closest greater or same value on left side for every element in array

Last Updated : 25 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of size n. For each element in the array, find the value wise closest element to its left that is greater than or equal to the current element. If no such element exists, return -1 for that position.

Examples:  

Input : arr[] = [10, 5, 11, 6, 20, 12]
Output : [-1, 10, -1, 10, -1, 20]
Explanation: The first element has nothing on the left side, so the answer for first is -1. 
Second, element 5 has 10 on the left, so the answer is 10. 
Third element 11 has nothing greater or the same, so the answer is -1. 
Fourth element 6 has 10 as value wise closest, so the answer is 10.
Similarly, we get values for the fifth and sixth elements.

Input : arr[] = [1, 2, 3, 4, 5]
Output : [-1, -1, -1, -1, -1]
Explanation: The given array is arranged in strictly increasing order, and all the elements on left of any element are smaller. Thus no index has any value greater or equal in its left.

Input : arr[] = [5, 4, 3, 2, 1]
Output : [-1, 5, 4, 3, 2]

[Naive Approach] – Using Nested Loops – O(n^2) Time and O(1) Auxiliary Space

A idea is to run two nested loops. We pick an outer element one by one. For every picked element, we traverse toward the left of it and find the closest (value-wise) greater element.

C++
#include <bits/stdc++.h>
using namespace std;

// Function to find the closest greater element
// on the left of every element of the array
vector<int> closestGreater(vector<int> &arr) {
    int n = arr.size();

    // to store the results
    vector<int> res(n, -1);

    for (int i = 1; i < n; i++) {

        // stores the minimum difference
        int diff = INT_MAX;

        // traverse left side to i-th element
        for (int j = 0; j < i; j++) {
            if (arr[j] >= arr[i])
                diff = min(diff, arr[j] - arr[i]);
        }

        // if greater or equal value exists
        if (diff != INT_MAX)
            res[i] = arr[i] + diff;
    }

    return res;
}

int main() {
    vector<int> arr = { 10, 5, 11, 6, 20, 12 };
    vector<int> res = closestGreater(arr);
    for(auto i:res) {
        cout<<i<<" ";
    }
    return 0;
}
Java
// Function to find the closest greater element
// on the left of every element of the array
import java.util.*;

class GfG {

    // Function to find the closest greater element
    static int[] closestGreater(int[] arr) {
        int n = arr.length;

        // to store the results
        int[] res = new int[n];
        for (int i = 0; i < n; i++) {
            res[i] = -1;
        }

        for (int i = 1; i < n; i++) {

            // stores the minimum difference
            int diff = Integer.MAX_VALUE;

            // traverse left side to i-th element
            for (int j = 0; j < i; j++) {
                if (arr[j] >= arr[i])
                    diff = Math.min(diff, arr[j] - arr[i]);
            }

            // if greater or equal value exists
            if (diff != Integer.MAX_VALUE)
                res[i] = arr[i] + diff;
        }

        return res;
    }

    public static void main(String[] args) {
        int[] arr = {10, 5, 11, 6, 20, 12};
        int[] res = closestGreater(arr);
        for (int i : res) {
            System.out.print(i + " ");
        }
    }
}
Python
# Function to find the closest greater element
# on the left of every element of the array
def closestGreater(arr):
    n = len(arr)

    # to store the results
    res = [-1] * n

    for i in range(1, n):

        # stores the minimum difference
        diff = float('inf')

        # traverse left side to i-th element
        for j in range(i):
            if arr[j] >= arr[i]:
                diff = min(diff, arr[j] - arr[i])

        # if greater or equal value exists
        if diff != float('inf'):
            res[i] = arr[i] + diff

    return res

if __name__ == "__main__":
    arr = [10, 5, 11, 6, 20, 12]
    res = closestGreater(arr)
    for i in res:
        print(i, end=" ")
C#
// Function to find the closest greater element
// on the left of every element of the array
using System;

class GfG {

    // Function to find the closest greater element
    static int[] closestGreater(int[] arr) {
        int n = arr.Length;

        // to store the results
        int[] res = new int[n];
        for (int i = 0; i < n; i++) {
            res[i] = -1;
        }

        for (int i = 1; i < n; i++) {

            // stores the minimum difference
            int diff = int.MaxValue;

            // traverse left side to i-th element
            for (int j = 0; j < i; j++) {
                if (arr[j] >= arr[i])
                    diff = Math.Min(diff, arr[j] - arr[i]);
            }

            // if greater or equal value exists
            if (diff != int.MaxValue)
                res[i] = arr[i] + diff;
        }

        return res;
    }

    static void Main() {
        int[] arr = {10, 5, 11, 6, 20, 12};
        int[] res = closestGreater(arr);
        foreach (int i in res) {
            Console.Write(i + " ");
        }
    }
}
JavaScript
// Function to find the closest greater element
// on the left of every element of the array
function closestGreater(arr) {
    let n = arr.length;

    // to store the results
    let res = new Array(n).fill(-1);

    for (let i = 1; i < n; i++) {

        // stores the minimum difference
        let diff = Infinity;

        // traverse left side to i-th element
        for (let j = 0; j < i; j++) {
            if (arr[j] >= arr[i])
                diff = Math.min(diff, arr[j] - arr[i]);
        }

        // if greater or equal value exists
        if (diff !== Infinity)
            res[i] = arr[i] + diff;
    }

    return res;
}

let arr = [10, 5, 11, 6, 20, 12];
let res = closestGreater(arr);
for (let i of res) {
    process.stdout.write(i + " ");
}

Output
-1 10 -1 10 -1 20 

[Expected Approach] – Using Set – O(n Log n) Time and O(n) Auxiliary Space

The idea is to use Tree Set (or Sorted Set or Set in C++) to store the elements on left of every element, ensuring that elements are stored in sorted order. Thereafter, for each element of the array arr[], find the closest greater or equal value in O(Log n) Time.

C++
#include <bits/stdc++.h>
using namespace std;

// Function to find the closest greater element
// on the left of every element of the array
vector<int> closestGreater(vector<int> &arr) {
    int n = arr.size();

    // to store the results
    vector<int> res(n, -1);

    // to store the elements in sorted order
    set<int> s;

    for (int i = 0; i < n; i++) {

        // First search in set
        auto it = s.lower_bound(arr[i]);

        // If greater or equal value exists
        if (it != s.end()) 
            res[i] = *it;

        // insert the current element in the set
        s.insert(arr[i]);
    }
    
    return res;
}

int main() {
    vector<int> arr = { 10, 5, 11, 6, 20, 12 };
    vector<int> res = closestGreater(arr);
    for(auto i:res) {
        cout<<i<<" ";
    }
    return 0;
}
Java
// Function to find the closest greater element
// on the left of every element of the array
import java.util.TreeSet;

class GfG {

    // Function to find the closest greater element
    static int[] closestGreater(int[] arr) {
        int n = arr.length;

        // to store the results
        int[] res = new int[n];
        for (int i = 0; i < n; i++) {
            res[i] = -1;
        }

        // to store the elements in sorted order
        TreeSet<Integer> s = new TreeSet<>();

        for (int i = 0; i < n; i++) {

            // First search in set
            Integer it = s.ceiling(arr[i]);

            // If greater or equal value exists
            if (it != null)
                res[i] = it;

            // insert the current element in the set
            s.add(arr[i]);
        }
        
        return res;
    }

    public static void main(String[] args) {
        int[] arr = {10, 5, 11, 6, 20, 12};
        int[] res = closestGreater(arr);
        for (int i : res) {
            System.out.print(i + " ");
        }
    }
}
Python
# Function to find the closest greater element
# on the left of every element of the array
import bisect

def closestGreater(arr):
    n = len(arr)

    # to store the results
    res = [-1] * n

    # to store the elements in sorted order
    s = []

    for i in range(n):

        # First search in set
        idx = bisect.bisect_left(s, arr[i])

        # If greater or equal value exists
        if idx < len(s):
            res[i] = s[idx]

        # insert the current element in the set
        bisect.insort(s, arr[i])
    
    return res

if __name__ == "__main__":
    arr = [10, 5, 11, 6, 20, 12]
    res = closestGreater(arr)
    for i in res:
        print(i, end=" ")
C#
// Function to find the closest greater element
// on the left of every element of the array
using System;
using System.Collections.Generic;

class GfG {

    // Function to find the closest greater element
    static int[] closestGreater(int[] arr) {
        int n = arr.Length;

        // to store the results
        int[] res = new int[n];
        for (int i = 0; i < n; i++) {
            res[i] = -1;
        }

        // to store the elements in sorted order
        SortedSet<int> s = new SortedSet<int>();

        for (int i = 0; i < n; i++) {

            // First search in set
            int? it = null;
            var view = s.GetViewBetween(arr[i], int.MaxValue);
            if (view.Count > 0) {
                it = view.Min;
            }

            // If greater or equal value exists
            if (it != null)
                res[i] = it.Value;

            // insert the current element in the set
            s.Add(arr[i]);
        }
        
        return res;
    }

    static void Main() {
        int[] arr = {10, 5, 11, 6, 20, 12};
        int[] res = closestGreater(arr);
        foreach (int i in res) {
            Console.Write(i + " ");
        }
    }
}
JavaScript
// Function to find the closest greater element
// on the left of every element of the array
function closestGreater(arr) {
    let n = arr.length;

    // to store the results
    let res = new Array(n).fill(-1);

    // to store the elements in sorted order
    let s = [];

    for (let i = 0; i < n; i++) {

        // First search in set
        let lo = 0, hi = s.length, candidate = null;
        while (lo < hi) {
            let mid = Math.floor((lo + hi) / 2);
            if (s[mid] < arr[i])
                lo = mid + 1;
            else {
                candidate = s[mid];
                hi = mid;
            }
        }

        // If greater or equal value exists
        if (candidate !== null)
            res[i] = candidate;

        // insert the current element in the set in sorted order
        s.splice(lo, 0, arr[i]);
    }

    return res;
}

let arr = [10, 5, 11, 6, 20, 12];
let res = closestGreater(arr);
for (let i = 0; i < res.length; i++) {
    process.stdout.write(res[i] + " ");
}

Output
-1 10 -1 10 -1 20 




Next Article
Article Tags :
Practice Tags :

Similar Reads