Ceiling Position (First >= Target)
This problem asks for the index of the first value in a sorted array that is greater than or equal to a target. If no value reaches the target, the answer should be -1.
The important detail is that you want the first valid position, not just any matching value. If several elements are large enough, you must return the leftmost one. That is why duplicates matter. In [1,2,4,4,7] with target 4, the correct answer is index 2, not 3.
For example, if nums = [2,3,3,3,9] and target = 1, the answer is 0 because the very first element already works. If nums = [3,5,6] and target = 7, the answer is -1 because every value is still too small.
So the task is to locate the leftmost index whose value is >= target, or return -1 when such an index does not exist.
Example Input & Output
The first element (2) is already at least 1, so the answer is 0.
No value is at least 7.
The first value that is at least 4 appears at index 2.
Algorithm Flow

Solution Approach
A strong method here is binary search. Because the array is sorted, we do not need to scan from left to right. We can repeatedly cut the search space in half.
The trick is to keep searching even after we find a value that is big enough. That value might be valid, but there could still be an earlier valid index to the left.
We start with two pointers around the full array and a variable to remember the best answer seen so far:
Then we check the middle position:
If nums[mid] >= target, then mid is a candidate answer, but we still move left to search for an earlier one. If nums[mid] < target, then everything on the left is too small, so we move rightward.
When the loop finishes, answer is the first valid index if one exists, otherwise it stays -1. This runs in O(log n) time and uses O(1) extra space.
Best Answers
class Solution {
public int ceiling_position(Object nums, Object target) {
int[] arr = (int[]) nums; int t = (int) target;
for (int i = 0; i < arr.length; i++) {
if (arr[i] >= t) return i;
}
return -1;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
