progress

~/problems / Greedy

Fewest benches along the trail

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

easy ~15 min

A park is putting benches along a straight trail with viewpoints at positions spots[i] (unsorted, possibly repeated). A bench can go at any position, even non-integer, and serves every viewpoint within reach metres (distance <= reach).

Write fewest_benches(spots: list[int], reach: int) -> int: the fewest benches that serve every viewpoint.

fewest_benches([1, 2, 6, 9, 10], 1)   # 3   benches at 2, 7 and 10 (or 2, 6 and 9, ...)
fewest_benches([4, 0, 8], 4)          # 1   one bench at 4 reaches 0 and 8
fewest_benches([5, 5, 5], 0)          # 1
fewest_benches([], 3)                 # 0

Up to 10^5 viewpoints, positions between -10^9 and 10^9.

⭐ Bonus: a speed test with 100,000 viewpoints earns a star in O(n log n).

Show hint

sort; the leftmost unserved viewpoint p needs a bench, and p + reach is the best place for it. Skip every viewpoint <= p + 2 * reach and repeat.

Topic: Greedy with sorting. Sort, then take the locally best choice; prove it with an exchange argument.

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