Find First Greater Element
You are given a sorted list of integers arranged in ascending order and a target value. Your task is to find the first element in the list that is strictly greater than the given target value. If such an element does not exist, return -1.
This challenge is designed to help you reason about order and relative comparisons within a sorted sequence. Imagine searching through a line of sorted numbers, where you are trying to find the first one that exceeds a certain threshold. The position of that number — not its value — is what you need to identify.
Every index in the list represents a valid position, starting from 0. If the target value is greater than or equal to all the numbers, there is no valid index, so the correct output is -1. This problem encourages you to think carefully about how comparisons work in sorted data and how you can efficiently pinpoint specific boundaries or transitions between values.
Algorithm Flow

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 problem.
