Find First Greater Element
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
No element is greater than 8.
The first element greater than 2 is 3, at index 3.
The first element greater than 4 is 5, at index 2.
Algorithm Flow

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.
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
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;
}
}
Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
