Python coding

Widest spacing for k sensors

A straight rail has mounting points at the distinct integer positions in spots, listed in no particular order. You must mount k sensors, each at a different point. Sensors that are close interfere, so you want the smallest distance between any two of them to be as large as possible. Return that largest possible smallest distance.

Constraints: 2 <= k <= len(spots), 0 <= spots[i] <= 10^9. Aim for O(n log n + n log R), where R = max(spots) − min(spots): trying every distance one at a time is O(n · R).

Besides the tests, one large input (1,000 spots, k = 500) with a ~150 ms limit (scaled to your device's speed): brute force won't pass.

  • widest_spacing([1,2,3,4,7], 3) → 3
  • widest_spacing([5,4,3,2,1,1000000000], 2) → 999999999
  • widest_spacing([1,2,8,4,9], 3) → 3
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

If a minimum gap d is achievable, every smaller gap is too. That monotonic yes/no question lets you binary search the answer itself.

Hint 2

Sort the spots. To check a gap, put a sensor at the first spot, then at every spot at least gap past the last sensor; the gap works if you place k.

Hint 3

You want the last gap that works, so on success set lo = mid and round mid up, (lo + hi + 1) // 2, or the search can loop forever.

Solution and why it works
pythonO(n log n + n log R) · O(n)
def widest_spacing(spots: list[int], k: int) -> int:
    spots = sorted(spots)

    def fits(gap: int) -> bool:          # greedy: each sensor at the leftmost spot the gap allows
        placed, last = 1, spots[0]
        for x in spots:
            if x - last >= gap:
                placed, last = placed + 1, x
        return placed >= k

    lo, hi = 1, (spots[-1] - spots[0]) // (k - 1)   # k - 1 gaps share the whole span
    while lo < hi:
        mid = (lo + hi + 1) // 2         # round up: lo = mid must still shrink the range
        if fits(mid):
            lo = mid
        else:
            hi = mid - 1
    return lo

Feasibility is monotonic: a gap that works keeps working as it shrinks, so binary search the largest one between 1 and span // (k - 1), the most that k - 1 gaps can share. Each check is a greedy O(n) pass: putting every sensor at the leftmost spot that keeps the gap never hurts the ones after it. The trap is searching for the last yes: with lo = mid, a rounded-down mid stops shrinking the range once hi = lo + 1.

Related lab: Loops in motion