Ceiling of every element in same array

Given an array of integers, find the closest smaller or same element for every element. If all elements are greater for an element, then print -1

Examples:

Input : arr[] = {10, 5, 11, 10, 20, 12}
Output : 10 10 12 10 -1 20
Note that there are multiple occurrences of 10, so ceiling of 10 is 10 itself.

Input : arr[] = {6, 11, 7, 8, 20, 12}
Output : 7 12 8 11 -1 20



A simple solution is to run two nested loops. We pick an outer element one by one. For every picked element, we traverse remaining array and find closest greater element. Time complexity of this solution is O(n*n)

An better solution is to sort the array and create a sorted copy, then do binary search for floor. We traverse the array, for every element we search for the first greater element. In C++ upper_bound() serves this purpose.

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of efficient algorithm to find
// floor of every element
#include <bits/stdc++.h>
using namespace std;
  
// Prints greater elements on left side of every element
void printPrevGreater(int arr[], int n)
{
    if (n == 1) {
        cout << "-1";
        return;
    }
  
    // Create a sorted copy of arr[]
    vector<int> v(arr, arr + n);
    sort(v.begin(), v.end());
  
    // Traverse through arr[] and do binary search for
    // every element.
    for (int i = 0; i < n; i++) {
  
        // Find the first element that is greater than
        // the given element
        auto it = upper_bound(v.begin(), v.end(), arr[i]);
  
        // Since arr[i] also exists in array, *(it-1)
        // will be same as arr[i]. Let us check *(it-2)
        // is also same as arr[i]. If true, then arr[i]
        // exists twice in array, so ceiling is same
        // same as arr[i]
        if ((it - 1) != v.begin() && *(it - 2) == arr[i]) {
  
            // If next element is also same, then there
            // are multiple occurrences, so print it
            cout << arr[i] << " ";
        }
  
        else if (it != v.end())
            cout << *it << " ";
        else
            cout << -1 << " ";
    }
}
  
/* Driver program to test insertion sort */
int main()
{
    int arr[] = {10, 5, 11, 10, 20, 12};
    int n = sizeof(arr) / sizeof(arr[0]);
    printPrevGreater(arr, n);
    return 0;
}

chevron_right


Output:

10 10 12 10 -1 20

Time Complexity : O(n Log n)
Auxiliary Space : O(n)



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.