Implement Lower Bound
Intuition
Complexity
Space Complexity
Time Complexity
Code
public static int lowerBound(int[] sortedArray, int arrayLength, int target) {
int left = 0, right = arrayLength - 1;
while (left <= right) {
int mid = (left + right) >> 1; // Compute middle index
// If target is found, move left to find first occurrence
if (sortedArray[mid] == target) {
while (mid - 1 >= 0 && sortedArray[mid - 1] == target) mid--;
return mid;
}
// If middle element is less than target, move right
if (sortedArray[mid] < target) {
left = mid + 1;
} else {
// Middle element is >= target, search left side
right = mid - 1;
}
}
// If target is not present, left points to the lower bound
return left;
}
Last updated