Given an integer array, the goal is to find the ceiling on the right for each element - the smallest number greater than or equal to it that appears after it. If no such number exists, return -1.
Example:
Input: arr[] = {10, 100, 200, 30, 120, 120}
Output: 30 120 -1 120 120 -1
Naive Approach
Follow the steps to find the ceiling of each element using the naive approach:
- Traverse the array from left to right.
- For each element, initialize a variable ceil as -1.
- Compare the current element with all elements to its right.
- Update ceil if a right-side element is ≥ current element and < current ceil (or if ceil is -1).
- After checking all elements to the right, print or store the value of ceil.
- Repeat the process for all elements in the array.
Implementation
public class CeilingNaive {
public static void main(String[] args)
{
int[] arr = { 10, 100, 200, 30, 120, 120 };
int n = arr.length;
for (int i = 0; i < n; i++) {
int ceil = -1;
for (int j = i + 1; j < n; j++) {
if (arr[j] >= arr[i]) {
// Update ceil if it's smaller than
// current ceil or if ceil is -1
if (ceil == -1 || arr[j] < ceil) {
ceil = arr[j];
}
}
}
System.out.print(ceil + " ");
}
}
}
Output
30 120 -1 120 120 -1
Efficient Approach Using TreeSet
Follow the below steps to find the ceiling of each element on its right side using a TreeSet:
- Initialize a TreeSet to keep track of elements seen so far.
- Create a result array to store the ceiling of each element.
- Traverse the input array from right to left.
- For each element, use TreeSet.ceiling(element) to find the smallest element greater than or equal to it.
- If a ceiling exists, store it in the result array; otherwise, store -1.
- Add the current element to the TreeSet so that future elements can find their ceiling.
- After processing all elements, print or return the result array.
Implementation
import java.util.*;
class GFG {
public static void printCeilingRight(int[] arr) {
int n = arr.length;
TreeSet<Integer> s = new TreeSet<>();
int[] res = new int[n];
for (int i = n - 1; i >= 0; i--) {
// Find the smallest element >= arr[i] in the TreeSet
Integer ceil = s.ceiling(arr[i]);
// If ceiling exists, store it; otherwise, store -1
if (ceil == null)
res[i] = -1;
else
res[i] = ceil;
// Add current element to TreeSet for future comparisons
s.add(arr[i]);
}
for (int x : res) {
System.out.print(x + " ");
}
}
public static void main(String[] args) {
int[] arr = {100, 50, 30, 60, 55, 32};
printCeilingRight(arr);
}
}
Output
-1 55 32 -1 -1 -1