Array Upper Bound — LeetCode 2774 Python Solution

EasyLeetCode PremiumJavaScript
Problem
#2774
Reading time
2 min

The 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.

Example

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

Python solution

Python
class Solution:
    def upperBound(self, nums: List[int], target: int) -> int:
        lo, hi = 0, len(nums)
        while lo < hi:
            mid = (lo + hi) // 2
            if nums[mid] <= target:
                lo = mid + 1
            else:
                hi = mid
        idx = lo - 1
        return idx if idx >= 0 and nums[idx] == target else -1

Complexity

MeasureComplexity
TimeO(\log n)
SpaceO(1) auxiliary

Pattern: Binary Search

Halve the search space each step — over an array, or over the answer itself. LeetCode 2774. Array Upper Bound is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The binary search guide has the Python template for the pattern and the 254 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2774. Array Upper Bound?
LeetCode 2774. Array Upper Bound is rated Easy on LeetCode.
What is the time complexity of LeetCode 2774. Array Upper Bound?
The Python solution on this page runs in O(\log n).
What is the space complexity of LeetCode 2774. Array Upper Bound?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2774. Array Upper Bound cover?
LeetCode 2774. Array Upper Bound is tagged JavaScript on LeetCode.
Is LeetCode 2774. Array Upper Bound a premium problem?
Yes. LeetCode 2774. Array Upper Bound is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview