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
Binary Search for Upper Bound1021222334Search Process:1. Initial: left=0, right=4, mid=2 โ†’ arr[2]=2 (target found!)โ€ข Save result=2, search right half for more occurrences2. Update: left=3, right=4, mid=3 โ†’ arr[3]=2 (target found again!)โ€ข Update result=3, continue searching right3. Update: left=4, right=4, mid=4 โ†’ arr[4]=3 (target < arr[4])โ€ข Search left half: right=34. Now left > right, exit loop and return result=3๐ŸŽฏ Key InsightWhen we find the target, we don't stop immediately!We save the index and continue searching right to find the last occurrence.Upper Bound = Index 3
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.
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
28.4K Views
Medium-High Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen