BudiBadu Logo

Find First Greater Element

Binary Search Medium 9 views
Like13

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.

Example 1:

Input: nums = [1, 3, 5, 7, 9], target = 4
Output: 2
Explanation: The first element greater than 4 is 5, at index 2.

Example 2:

Input: nums = [2, 4, 6, 8], target = 8
Output: -1
Explanation: No element is greater than 8.

Example 3:

Input: nums = [1, 2, 2, 3], target = 2
Output: 3
Explanation: The first element greater than 2 is 3, at index 3.

Algorithm Flow

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

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