# Find closest smaller value for every element in array in C++

C++Server Side ProgrammingProgramming

Here we will see how to find the closest value for every element in an array. If an element x has the next element that is larger than it, and also present in the array, then that will be the greater value of that element. If the element is not present, then return -1. Suppose the array elements are [10, 5, 11, 6, 20, 12], then the greater elements are [11, 6, 12, 10, -1, 20]. As 20 has not greater value in the array, then print -1.

To solve this, we will use the settings in C++ STL. The set is implemented using the binary tree approach. In binary tree always the in-order successor is the next larger element. So we can get the element in O(log n) time.

## Example

Live Demo

#include<iostream>
#include<set>
using namespace std;
void nearestGreatest(int arr[], int n) {
set<int> tempSet;
for (int i = 0; i < n; i++)
tempSet.insert(arr[i]);
for (int i = 0; i < n; i++) {
auto next_greater = tempSet.upper_bound(arr[i]);
if (next_greater == tempSet.end())
cout << -1 << " ";
else
cout << *next_greater << " ";
}
}
int main() {
int arr[] = {10, 5, 11, 6, 20, 12};
int n = sizeof(arr) / sizeof(arr);
nearestGreatest(arr, n);
}

## Output

11 6 12 10 -1 20