The lower bound of a number x in a sorted array arr is the smallest index idx such that arr[idx] >= x. If all elements in the array are less than x, the lower bound is n (the size of the array).
If all numbers are smaller than x, then n should be the lower_bound of x, where n is the size of the given array.
Input:
arr = [1, 3, 5, 7, 9]
x = 6
Output:
Lower bound of 6 is at index 3
Input:
arr = [2, 4, 6, 8, 10]
x = 12
Output:
Lower bound of 12 is at index 5
public class Solution {
public static int lowerBound(int[] arr, int x) {
int lb = arr.length;
int left = 0;
int right = arr.length - 1;
while (left <= right) {
int mid = left + ((right - left) / 2);
if (arr[mid] >= x) {
lb = mid;
right = mid - 1;
} else {
left = mid + 1;
}
}
return lb;
}
}The upper bound of a number x in a sorted array arr is the smallest index idx such that arr[idx] > x. If all elements in the array are less than or equal to x, the upper bound is n (the size of the array).
If the greater value does not exist then our answer is n, Where n is the size of the given array.
Input:
arr = [1, 2, 4, 6, 8]
x = 5
Output:
Upper bound of 5 is at index 3
Input:
arr = [1, 3, 5, 7, 9]
x = 2
Output:
Upper bound of 2 is at index 1
public class Solution {
public static int upperBound(int[] arr, int x) {
int ub = arr.length;
int left = 0;
int right = arr.length - 1;
while (left <= right) {
int mid = left + ((right - left) / 2);
if (arr[mid] > x) {
right = mid - 1;
ub = mid;
} else {
left = mid + 1;
}
}
return ub;
}
}