Skip to content
thesarfo

Reference

Upper Bound

Finding the smallest index where arr[i] > x, the strictly-greater counterpart to lower bound.

views 0

Same idea as lower bound, but for the first index i where arr[i] > x (strictly greater, not greater-or-equal).

public static int upperBound(int[] arr, int n, int x){
int low = 0, high = n - 1;
int ans = n;
while(low <= high){
int mid = (low + high) / 2;
if(arr[mid] > x){
ans = mid;
high = mid - 1;
} else{
low = mid + 1;
}
}
return ans;
}
CriterionLower BoundUpper Bound
Conditionarr[i] >= xarr[i] > x
Search left whenarr[mid] >= xarr[mid] > x
Final answersmallest i with arr[i] >= xsmallest i with arr[i] > x