Array Upper Bound - Problem

Write code that enhances all arrays such that you can call the upperBound() method on any array and it will return the last index of a given target number.

nums is a sorted ascending array of numbers that may contain duplicates. If the target number is not found in the array, return -1.

The method should be added to Array.prototype so it can be called on any array.

Input & Output

Example 1 — Basic Case with Duplicates
$ Input: nums = [1,2,2,2,3], target = 2
Output: 3
💡 Note: Target 2 appears at indices 1, 2, 3. The last occurrence is at index 3.
Example 2 — Single Occurrence
$ Input: nums = [1,3,5,7,9], target = 5
Output: 2
💡 Note: Target 5 appears only once at index 2, so that's the last occurrence.
Example 3 — Target Not Found
$ Input: nums = [1,3,5,7,9], target = 4
Output: -1
💡 Note: Target 4 is not present in the array, so return -1.

Constraints

  • 1 ≤ nums.length ≤ 104
  • -104 ≤ nums[i] ≤ 104
  • nums is sorted in ascending order
  • -104 ≤ target ≤ 104

Visualization

Tap to expand
Array Upper Bound: Find Last Index of TargetInput Array:1222301234Target: 2All occurrences of target 22Last occurrenceOutput: 3
Understanding the Visualization
1
Input
Sorted array with duplicates and target value
2
Process
Find the rightmost occurrence of target
3
Output
Index of last occurrence or -1 if not found
Key Takeaway
🎯 Key Insight: Use binary search to find upper bound, then check if target exists at that position minus one
Asked in
Google 25 Microsoft 20 Amazon 18
23.4K Views
Medium 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