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

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

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.

 `// C++ implementation of efficient algorithm to find ` `// floor of every element ` `#include ` `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; ` `} `

Output:

```10 10 12 10 -1 20
```

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

My Personal Notes arrow_drop_up