Code Logo

Ceiling Position (First >= Target)

Published at05 Jan 2026
Easy 10 views
Like12

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

Example 1
Input
nums = [2, 3, 3, 3, 9], target = 1
Output
0
Explanation

The first element (2) is already at least 1, so the answer is 0.

Example 2
Input
nums = [3, 5, 6], target = 7
Output
-1
Explanation

No value is at least 7.

Example 3
Input
nums = [1, 2, 4, 4, 7], target = 4
Output
2
Explanation

The first value that is at least 4 appears at index 2.

Algorithm Flow

Recommendation Algorithm Flow for Ceiling Position (First >= Target)
Recommendation Algorithm Flow for Ceiling Position (First >= Target)

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:

let left = 0;
let right = nums.length - 1;
let answer = -1;

Then we check the middle position:

while (left <= right) {
  const mid = Math.floor((left + right) / 2);

  if (nums[mid] >= target) {
    answer = mid;
    right = mid - 1;
  } else {
    left = mid + 1;
  }
}

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

java
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;
    }
}