VOOZH about

URL: https://www.geeksforgeeks.org/java/ceiling-on-right-in-java/

⇱ Ceiling on right in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Ceiling on right in Java

Last Updated : 28 Jan, 2026

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


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


Output
-1 55 32 -1 -1 -1 
Comment
Article Tags:
Article Tags: