Talentd
FleetCode

2774. Array Upper Bound

Easy82.0% acceptancePremium elsewhere, free here

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.

Example 1:

Input: nums = [3,4,5], target = 5
Output: 2
Explanation: Last index of target value is 2

Example 2:

Input: nums = [1,4,5], target = 2
Output: -1
Explanation: Because there is no digit 2 in the array, return -1.

Example 3:

Input: nums = [3,4,6,6,6,6,7], target = 6
Output: 5
Explanation: Last index of target value is 5

Constraints:

  • 1 <= nums.length <= 104
  • -104 <= nums[i], target <= 104
  • nums is sorted in ascending order.
Follow up: Can you write an algorithm with O(log n) runtime complexity?

Hints open one at a time

Hint 1
Inside the Array.prototype.upperBound function you have access to the "this" keyword. You can access array elements, values, and methods. For example "this[0]", "this[1]", "this.length", "this.map()", etc.
Hint 2
The most efficient way to solve this problem is with binary search.
Hint 3
Choose the middle element and check if it's less than or equal to the goal value. If so, you can rule out the left side of the array.
20:06
Still stuck?Read the written solution, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def solve(self):
3 pass
4
Starter codePython 3Spaces: 4
Examples
Input
[3,4,5]
5
Input
[1,4,5]
2
Input
[3,4,6,6,6,6,7]
6
Your code is saved on this device.Solution