progress

~/problems / Binary search / Binary search

Upper bound: first index past a value

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~10 min

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. No bisect or list.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 each x in xs (call an upperBound helper in a loop).
Show hint

the only difference from lower bound: does an element equal to x send you left or right?

Topic: Binary search. lo/hi invariants, lower vs upper bound, rotated arrays, bisect.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc