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 - Binary Search INPUT nums (sorted ascending) 1 i=0 2 i=1 2 i=2 2 i=3 3 i=4 target = 2 Input Values nums = [1,2,2,2,3] target = 2 Find LAST index of target ALGORITHM STEPS 1 Initialize Pointers left=0, right=n-1 result=-1 (not found) 2 Binary Search Loop while (left <= right) mid = (left+right)/2 3 Compare & Update if nums[mid]==target: result=mid, left=mid+1 4 Adjust Search Range if target < nums[mid]: right = mid - 1 else: left = mid + 1 Search Right for Upper Bound Keep moving right when found FINAL RESULT 1 2 2 2 3 Upper Bound Output 3 Verification nums[3] = 2 = target [OK] nums[4] = 3 != target [OK] Index 3 is LAST occurrence Time: O(log n) Key Insight: To find the UPPER BOUND (last occurrence), when target is found, save the index but continue searching RIGHT (left = mid + 1). This ensures we find the rightmost occurrence. Add method to Array.prototype for universal access. Binary search reduces O(n) linear scan to O(log n) by halving search space each iteration. TutorialsPoint - Array Upper Bound | Optimal Solution (Binary Search)
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