

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find closest smaller value for every element in array in C++
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
#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[0]); nearestGreatest(arr, n); }
Output
11 6 12 10 -1 20
- Related Questions & Answers
- Find closest value for every element in array in C++
- Find closest greater value for every element in array in C++
- Find the closest and smaller tidy number in C++
- Find closest number in array in C++
- Find the closest value of an array in JavaScript
- Next Smaller Element in C++
- Find maximum sum taking every Kth element in the array in C++
- Find the closest element in Binary Search Tree in C++
- Find last element after deleting every second element in array of n integers in C++
- Floor of every element in same array in C++
- Find k closest elements to a given value in C++
- Find k closest numbers in an unsorted array in C++
- Find closest index of array in JavaScript
- Find the element that appears once in an array where every other element appears twice in C++
- Find K Closest Elements in C++
Advertisements