Code Logo

Find First Greater Element

Published at05 Jan 2026
Medium 12 views
Like13

This problem asks for the index of the first element that is strictly greater than a target value in a sorted array.

The answer is an index, not the value itself. If the array never goes above the target, the answer should be -1. Equality does not count here, so values that are exactly the same as the target must be skipped.

For example, in [1,2,2,3] with target 2, the answer is 3 because the first value bigger than 2 is 3 at index 3. In [2,4,6,8] with target 8, the answer is -1 because no value is greater than 8.

So the task is to find the earliest position where the array finally becomes larger than the target.

Example Input & Output

Example 1
Input
nums = [2, 4, 6, 8], target = 8
Output
-1
Explanation

No element is greater than 8.

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

The first element greater than 2 is 3, at index 3.

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

The first element greater than 4 is 5, at index 2.

Algorithm Flow

Recommendation Algorithm Flow for Find First Greater Element
Recommendation Algorithm Flow for Find First Greater Element

Solution Approach

This is a clean binary search for the first position where nums[i] > target.

We keep a search window and shrink it based on the middle value. If nums[mid] is already greater than the target, then this position could be the answer, but there might be an earlier one, so we move left. Otherwise, we need to search to the right.

let left = 0;
let right = nums.length;

while (left < right) {
  const mid = Math.floor((left + right) / 2);
  if (nums[mid] > target) {
    right = mid;
  } else {
    left = mid + 1;
  }
}

After the loop, left is the first index where the value is greater than the target. If left === nums.length, then no such element exists and the answer is -1.

This runs in O(log n) time and uses O(1) extra space.

Best Answers

java

class Solution {
    public int find_first_greater(int[] nums, int target) {
        int l = 0, r = nums.length - 1;
        int ans = -1;
        while (l <= r) {
            int mid = l + (r - l) / 2;
            if (nums[mid] > target) {
                ans = mid;
                r = mid - 1;
            } else {
                l = mid + 1;
            }
        }
        return ans;
    }
}