Problem Description
Given a sorted (in ascending order) array of numbers that may contain duplicates, implement a method named upperBound() that returns the last index of a given target number. If the target number is not present, return -1.
Key Insights
- The array is sorted, which allows us to use binary search to achieve O(log n) runtime.
- The goal is to find the rightmost (last) occurrence of the target if it exists.
- If the target does not exist in the array, the function should return -1.
Space and Time Complexity
Time Complexity: O(log n) Space Complexity: O(1)
Solution
We can solve this problem using a binary search variant designed to find the last occurrence of the target:
- Initialize two pointers, low and high, to the start and end of the array.
- Repeatedly compute the middle index.
- If the target is found, move the low pointer to search to the right to ensure it is the last occurrence.
- If the target is less than the middle element, adjust the high pointer.
- If the target is greater than the middle element, adjust the low pointer.
- After binary search terminates, verify whether the found index contains the target.
- Return the index if found; otherwise, return -1.
This approach uses no extra space (apart from a few variables) and performs in logarithmic time.