878949. Implement Upper Bound
Here is a detailed Markdown blog post for the GeeksforGeeks problem "Implement Upper Bound":
Implement Upper Bound
Summary
Given an array of unique integers, implement an algorithm to find the upper bound of a given target element. The upper bound is defined as the largest index i such that the element at index i is less than or equal to the target.
The key concepts involved are binary search and arrays.
Detailed Explanation
To solve this problem, we can use a modified binary search algorithm. The idea is to start from both ends of the array (low and high) and move towards each other until they meet.
Here's a step-by-step breakdown of the solution:
- Initialize two pointers, low and high, to the start and end of the array respectively.
- Calculate the mid index using the formula
mid = (low + high) / 2. - Compare the element at the mid index with the target element. If it is less than or equal to the target, update the low pointer to
mid + 1. Otherwise, update the high pointer tomid - 1. - Repeat steps 2-3 until low and high meet.
- The upper bound is the largest index i such that the element at index i is less than or equal to the target.
The time complexity of this algorithm is O(log n), where n is the size of the array, because we are effectively performing a binary search on the array. The space complexity is O(1) as we only use a constant amount of space.
Optimized Solutions
Java
java
public int upperBound(int[] arr, int target) {
int low = 0;
int high = arr.length - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] <= target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return low;
}
Python
python
def upper_bound(arr, target):
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] <= target:
low = mid + 1
else:
high = mid - 1
return low
C++
cpp
int upperBound(int* arr, int n, int target) {
int low = 0;
int high = n - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] <= target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return low;
}
JavaScript
javascript
function upperBound(arr, target) {
let low = 0;
let high = arr.length - 1;
while (low <= high) {
const mid = Math.floor((low + high) / 2);
if (arr[mid] <= target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return low;
}
Not available