BudiBadu Logo

Find First Greater Element

Binary Search Medium 10 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.

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