Introduction
This blog will learn to find the closest greater value for every element in the array. So let's suppose we have an array. We have to find the closest greater value for the element in the array.
For example-
Given Array- 2 5 3 4 20 9
After removing duplicates from the unsorted linked list- 3 9 4 5 -1 20
Explanation-
The closest greater value for 2 is 3
The closest greater value for 5 is 9
The closest greater value for 3 is 4
The closest greater value for 4 is 5
There is no greater value for 20, so we print -1
The closest greater value for 9 is 20
To find the closest greater value for every element in the array, we will start with the naive approach to use two loops. After that, we will discuss the optimized approach at the cost of some space.
Naive Approach
In the naive approach to finding the closest greater value for every element, We have to use two nested loops. One is for indexing every element. The second loop is for finding the next greater element in the array.
Algorithm
- We have a given array, and we must find the closest greater value for every element.
-
Iterate through the array one by one for each index.
- We have to find the closest greater value.
- Iterate the whole array again and save the closest greater value from the array.
- Print that saves value for every element.
Implementation in C++
#include <bits/stdc++.h>
using namespace std;
//closest greater value for every element
void closest_greater_value(int n, int arr[]){
// n is size of array
for(int i = 0; i<n ; i++) { // for traversing ever element
int closest_greater = -1; // intialise with -1
for(int j=0 ;j<n; j++) { // loop for finding closest greater value to arr[i]
//if we are on same index
if(i == j) continue;
// find any greater element to arr[i] then minimise its value
if(arr[j] > arr[i]){
if( closest_greater == -1)
closest_greater = arr[j];
else
closest_greater=min(closest_greater,arr[j]);
}
}
cout<<closest_greater<<” “;
}
}
//Driver function.
int main()
{
int n= 6; // size of array
int arr[]={10, 5, 11, 6, 20, 12} ; // array intialising
closest_greater_value(n,arr);
}
Input-
6
10 5 11 6 20 12
Output-
11 6 12 10 -1 20
Complexity Analysis
The time complexity of this approach is- O(N2). We traverse via two nested loops for every element.
The space complexity of this approach is- O(1).




