Array Upper Bound - Problem
Extend the JavaScript Array prototype by implementing an upperBound() method that finds the last occurrence of a target element in a sorted array.
Your task is to enhance all arrays so they have an upperBound(target) method that returns the highest index where the target value appears. If the target is not found, return -1.
Given: A sorted ascending array of numbers that may contain duplicates
Find: The last index of the target number
Return: Index of last occurrence, or -1 if not found
Example: [1, 2, 2, 2, 3].upperBound(2) should return 3 (the last index where 2 appears)
Input & Output
example_1.js โ Basic Usage
$
Input:
arr = [1, 2, 2, 2, 3], target = 2
โบ
Output:
3
๐ก Note:
The target 2 appears at indices 1, 2, and 3. The upper bound (last occurrence) is at index 3.
example_2.js โ Single Occurrence
$
Input:
arr = [1, 2, 3, 4, 5], target = 3
โบ
Output:
2
๐ก Note:
The target 3 appears only once at index 2, so the upper bound is also 2.
example_3.js โ Target Not Found
$
Input:
arr = [1, 3, 5, 7, 9], target = 4
โบ
Output:
-1
๐ก Note:
The target 4 is not present in the array, so we return -1 as specified.
Constraints
- 1 โค arr.length โค 104
- -104 โค arr[i] โค 104
- arr is sorted in ascending order
- -104 โค target โค 104
- Array may contain duplicate elements
Visualization
Tap to expand
Understanding the Visualization
1
Initialize Search Space
Set left and right pointers to define our search boundaries
2
Find Middle Element
Calculate the middle index and compare with target
3
Adjust Search Direction
If target found, save index but continue searching right for later occurrences
4
Return Last Found Index
When search space is exhausted, return the rightmost occurrence found
Key Takeaway
๐ฏ Key Insight: The binary search modification continues searching right when target is found, ensuring we locate the rightmost occurrence efficiently in O(log n) time.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code