# Ceiling in right side for every element in Array

Question: Write a program in C++ to find ceiling on right side for every element of an array.

Given: An array of integers.

Problem: Find the closest greater element for every element. If there is no greater element then print -1

Examples:

```Input : arr[] = {10, 5, 11, 10, 20, 12}
Output : 10 10 12 12 -1 -1

Input : arr[] = {50, 20, 200, 100, 30}
Output : 100 30 -1 -1 -1```

Solutions:

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

A better solution is to use sorting. We sort all elements, then for every element, traverse toward right until we find a greater element (Note that there can be multiple occurrences of an element).

An efficient solution is to use Self Balancing BST (Implemented as set in C++). In a Self Balancing BST, we can do both insert and ceiling operations in O(Log n) time.

### C++ Program to find ceiling on right side for every element of array:

```// C++ program to find ceiling on right side for
// every element.
#include <bits/stdc++.h>
using namespace std;

void closestGreater(int arr[], int n)
{
set<int> s;
vector<int> ceilings;

// Find smallest greater or equal element
// for every array element
for (int i = n - 1; i >= 0; i--) {
auto greater = s.lower_bound(arr[i]);
if (greater == s.end())
ceilings.push_back(-1);
else
ceilings.push_back(*greater);
s.insert(arr[i]);
}

for (int i = n - 1; i >= 0; i--)
cout << ceilings[i] << " ";
}

int main()
{
int arr[] = { 50, 20, 200, 100, 30 };
closestGreater(arr, 5);
return 0;
}
```

Output:

`100 30 -1 -1 -1`

Time Complexity: O(n Log n)

Comment in case of any issues, concern or suggestion regarding ‘C++ Program to find ceiling on right side for every element of an array’.