881725. upper and lower bounds of an element
Basic
Upper and Lower Bounds of an Element
Summary
Given a sorted array, find the upper and lower bounds of a target element. The problem requires you to return the indices of the first and last occurrences of the given element in the array. The array is sorted in ascending order.
Detailed Explanation
To solve this problem, we can use the following algorithm:
- Initialize two pointers,
lowandhigh, to the start and end of the array respectively. - Calculate the middle index of the current subarray using
(low + high) / 2. - Compare the element at the middle index with the target element.
- If the elements are equal, update the lower bound by moving
lowup to the middle index, and repeat steps 2-4 until the elements are no longer equal. - Once the elements are no longer equal, move
highdown to the previous middle index, and repeat steps 2-4 until the elements are equal again orhighis less thanlow. - The lower bound is now at
low, and the upper bound is athigh - 1.
Time complexity: O(log n), where n is the size of the array. Space complexity: O(1).
Here's a step-by-step breakdown:
+---------------+
| low |
+---------------+
|
v
+---------------+ +---------------+
| elements | | elements |
| (0, 1, 2, ... | | (... , x, y, z)|
| ) | | ) |
+---------------+ +---------------+
^
|
+---------------+
| high |
+---------------+
Optimized Solutions
Java
public int[] upperAndLowerBounds(int[] arr, int target) {
int low = binarySearch(arr, target);
if (low == -1) return new int[] {-1, -1};
int high = low;
while (arr[high] == target) high++;
return new int[]{low, high-1};
}
private int binarySearch(int[] arr, int target) {
int low = 0, high = arr.length - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] == target) return mid;
else if (arr[mid] < target) low = mid + 1;
else high = mid - 1;
}
return -1;
}