Optimal 1D Coverage: Minimize Worst-Case Distance to k Centers
Greedy & IntervalsAuto-graded · 22 test casesLast updated
Tests binary-search-on-answer combined with a greedy interval feasibility check to solve the 1D k-center minimax placement problem.
Optimal 1D Coverage: Minimize Worst-Case Distance to k Centers
You have a list of points on a number line and a budget of k centers you can place anywhere on the line. The coverage radius of a placement is the largest absolute distance any point must travel to reach its nearest center. Your goal is to choose the positions of the k centers to make that worst-case distance as small as possible.
Return a dictionary with two keys:
"radius": the minimized worst-case distancer*(afloat; it will always be a multiple of0.5)."centers": a list of exactlykfloats giving center positions that achiever*, produced by a left-to-right greedy sweep. If fewer thankcenters are needed, repeat the last center until the list has lengthk.
How placement works
A single center at position c with radius r covers every point whose distance to c is at most r, i.e., every point in the interval [c − r, c + r]. You want all n points covered by the union of the k such intervals, with r as small as possible.
Determining which centers to output
Once the optimal radius is known, use the following greedy left-to-right rule to find the centers:
- Sort the points.
- Find the leftmost uncovered point
p. - Place a center at
p + r*, covering everything in[p, p + 2r*]. - Repeat from step 2 until all points are covered.
This greedy sweep produces the centers in the required order.
Constraints
1 ≤ k ≤ n ≤ 2 × 10⁵-10⁹ ≤ points[i] ≤ 10⁹- Point values are integers and may repeat.
r*is always an exact multiple of0.5; the returned"radius"must match this exactly.- The returned
"centers"list must have length exactlyk.
Examples
Example 1
Input: place_centers_min_radius([1, 2, 3], 1)
Output: {'radius': 1, 'centers': [2]}
Example 2
Input: place_centers_min_radius([0, 0, 10, 10], 2)
Output: {'radius': 0, 'centers': [0, 10]}
Example 3
Input: place_centers_min_radius([-5, -4, 10], 2)
Output: {'radius': 0.5, 'centers': [-4.5, 10.5]}
Example 4
Input: place_centers_min_radius([0, 100], 1)
Output: {'radius': 50, 'centers': [50]}
Hints
Hint 1
Sort the points first. The optimal radius only depends on the span of each greedy group, so think about binary-searching on twice the radius (an integer) rather than on the radius itself.
Hint 2
For a fixed candidate doubled-radius R2, a greedy left-to-right sweep decides feasibility in O(n): anchor an interval at the leftmost uncovered point, skip everything it covers, and count intervals used. If the count is ≤ k, R2 is feasible.
Hint 3
To avoid all floating-point issues, binary-search over integer values of 2r on [0, 2*(max − min)]. Every comparison in the greedy stays between integers. Divide by 2.0 only at the very end when writing the output.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Reduction to interval covering
A center at position c with radius r covers every point in [c − r, c + r], an interval of length 2r. Placing k centers at radius r is equivalent to covering all points with k intervals of length 2r. The problem therefore reduces to: find the smallest length L = 2r such that k intervals of that length cover every point.
Greedy feasibility check
Sort the points. For a fixed candidate length L, one left-to-right scan decides whether k intervals suffice:
- Take the leftmost uncovered point
p. - Place an interval
[p, p + L](center atp + L/2). - Skip all points that fall inside this interval.
- Repeat, counting intervals.
If the count is ≤ k, L is feasible. This greedy is optimal by an exchange argument: any valid placement covering the leftmost point can be shifted right until its left edge sits on that point, covering at least as many remaining points. The argument applies inductively to each subsequent group, so the greedy never uses more intervals than any valid solution.
Binary search on the doubled radius
Feasibility is monotone — if L works, any larger L also works — so binary search applies. To avoid floating-point arithmetic entirely, binary-search over integer r2 = 2r. Every comparison in the greedy asks whether points[j] − points[i] ≤ 2r, which is a pure integer comparison when r2 is an integer. The optimal r2 is therefore an integer, and r* = r2 / 2 is an exact half-integer, safe as a Python float.
The search range is [0, 2*(max − min)], giving at most log₂(4 × 10⁹) ≈ 32 iterations.
Center reconstruction
Once the optimal r2 is known, a second greedy sweep rebuilds the centers. Each center sits at first + r2/2, where first is the leftmost uncovered point. Storing this as the integer 2*first + r2 in doubled coordinates avoids any rounding until the final division by 2. If fewer than k centers are produced, the list is padded by repeating the last one; duplicate centers never increase the radius.
Complexity
- Sorting: O(n log n)
- Each feasibility check: O(n) with a single forward pass
- Binary search: O(log(max − min)) ≈ 32 iterations
- Total time: O(n log n + n log R) where R = max − min ≤ 2 × 10⁹
- Extra space: O(1) beyond the sorted array, plus O(k) for the output list
Edge cases
- All points equal, or
k ≥ n: optimal doubled radius is 0, sor* = 0. k = 1: one interval must cover everything;r* = (max − min) / 2.- Negative coordinates: sorting and integer arithmetic handle them without any special treatment.
- Repeated values: covered by the same interval as their neighbors; the greedy skips them naturally.
Reference solution
from typing import List, Dict
def place_centers_min_radius(points: List[int], k: int) -> Dict[str, object]:
pts = sorted(points)
n = len(pts)
upper = pts[-1] - pts[0]
# Work in doubled coordinates so every comparison stays integer.
# r2 represents the radius r = r2 / 2.
# An interval of radius r around center c covers [c-r, c+r], length 2r.
# Anchoring the left edge at point `first`, the interval covers
# [first, first + 2r], whose right edge in doubled coords is
# 2*first + 2*r2 = 2*first + 4r. A point p is covered iff 2*p <= 2*first + 2*r2.
def feasible(r2: int) -> bool:
used = 0
i = 0
while i < n:
used += 1
if used > k:
return False
first = pts[i]
right2 = 2 * first + 2 * r2 # rightmost covered point in doubled coords
i += 1
while i < n and 2 * pts[i] <= right2:
i += 1
return True
# Binary-search the smallest feasible r2 = 2r.
# Upper bound: r2 = 2*upper means r = upper = max-min, which one center covers.
lo, hi = 0, 2 * upper
while lo < hi:
mid = (lo + hi) // 2
if feasible(mid):
hi = mid
else:
lo = mid + 1
r2 = lo # optimal doubled radius
# Reconstruct centers with the same greedy sweep.
# Center for a group starting at `first` sits at first + r = first + r2/2,
# stored in doubled coords as 2*first + r2.
centers2: List[int] = []
i = 0
while i < n:
first = pts[i]
centers2.append(2 * first + r2) # center in doubled coords
right2 = 2 * first + 2 * r2 # rightmost covered point in doubled coords
i += 1
while i < n and 2 * pts[i] <= right2:
i += 1
# Pad to exactly k centers; duplicates never increase the radius.
while len(centers2) < k:
centers2.append(centers2[-1])
return {
"radius": r2 / 2.0,
"centers": [c / 2.0 for c in centers2],
}