Write upper_bound(a: list[int], x: int) -> int that returns the first index i with a[i] > x, or len(a) if there's none. a is sorted and may have duplicates, so upper_bound(a, x) - lower_bound(a, x) counts the copies of x (where lower_bound(a, x) is the first index i with a[i] >= x).
a = [2, 4, 4, 4, 9]
upper_bound(a, 4) # 4 (9 is the first value > 4)
upper_bound(a, 5) # 4
upper_bound(a, 1) # 0
upper_bound(a, 9) # 5 (= len(a))
len(a) <= 10^6. Nobisectorlist.index: write the loop.- ⭐ Bonus: a speed test with many calls earns a star at O(log n) per call.
- C++ / Java: write
upperBoundAll(a, xs), returning the answer for eachxinxs(call anupperBoundhelper in a loop).
Show hint
the only difference from lower bound: does an element equal to x send you left or right?