Array Upper Bound — LeetCode 2774 Python Solution
- Problem
- #2774
- Pattern
- Binary Search
- Reading time
- 2 min
- Source
- leetcode.com
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
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 -1Complexity
| Measure | Complexity |
|---|---|
| Time | O(\log n) |
| Space | O(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.