VOOZH about

URL: https://www.geeksforgeeks.org/dsa/closest-greater-or-same-value-on-left-side-for-every-element-in-array/

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


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 11 Jul, 2025

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.


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.


Output
-1 10 -1 10 -1 20 


Comment
Article Tags:
Article Tags: