progress

~/problems / Binary search / Prefix sums + binary search

Which bucket holds position x

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

easy basics ~10 min

Buckets of sizes sizes[0], sizes[1], ... sit end to end on a number line from 0: bucket 0 covers 0 .. sizes[0] - 1, bucket 1 the next sizes[1] positions, and so on.

Write find_buckets(sizes: list[int], positions: list[int]) -> list[int] returning the bucket index for each position.

# sizes [3, 1, 2] cover:  0 1 2 | 3 | 4 5
find_buckets([3, 1, 2], [0, 2, 3, 4, 5])   # [0, 0, 1, 2, 2]

# the empty bucket 1 never owns anything
find_buckets([2, 0, 2], [1, 2])            # [0, 2]

Up to 10^5 buckets and positions; every position is in [0, sum(sizes)). ⭐ Bonus: a speed test earns a star at O(log n) per position.

Show hint

with ends = list(itertools.accumulate(sizes)), the answer is bisect.bisect_right(ends, x).

Topic: Prefix sums + binary search. Weighted sampling: bisect into cumulative weights.

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