Minimum Guards to Cover All Museum Gallery Segments
Greedy & IntervalsAuto-graded · 17 test casesLast updated
Tests ability to apply a sweep-line with a greedy exchange argument to optimally place point guards that each cover a fixed-radius interval on a 1-D gallery.
Minimum Guards to Cover All Museum Gallery Segments
A museum has a long corridor modelled as a number line. Several exhibits are placed along it; each exhibit occupies a closed segment [l, r] (with l ≤ r) that must be fully covered by at least one guard.
You may place guards anywhere on the number line (including non-integer positions). Each guard has a coverage radius d: a guard placed at position p covers every point in [p - d, p + d].
Find the minimum number of guards needed so that every exhibit segment is fully covered (i.e., every point of every segment [l, r] lies within the coverage interval of at least one guard).
Task
Implement:
def min_guards(segments: list[list[int]], d: int) -> int:
segments: a list of segments, each given as[l, r]withl ≤ r.d: the non-negative integer coverage radius of each guard.- Returns the minimum number of guards required to cover all segments, or
-1if it is impossible (i.e., some segment is longer than2dand therefore cannot be covered by any single guard — but note a segment may be covered by multiple guards; see constraints for when-1applies).
How coverage works
A segment [l, r] is fully covered if and only if every point x ∈ [l, r] belongs to [p - d, p + d] for at least one guard position p. Because a single guard covers a contiguous interval of length 2d, a segment longer than 2d cannot be covered by a single guard. However, multiple guards can cooperate to cover a long segment — there is no restriction on the number of guards or their placement, and their coverage intervals may overlap.
Wait — re-read: multiple guards can cooperate. So -1 is actually never returned (you can always add more guards). Therefore the function always returns a non-negative integer.
Clarification on
-1: The return value is always ≥ 0. Ifsegmentsis empty, return0.
Key insight
Because guards can cooperate, no segment is impossible to cover. The challenge is finding the minimum count via an optimal greedy sweep.
Approach hint
Think about processing segments sorted by their right endpoint and greedily placing each guard as far right as possible while still covering the current uncovered portion.
Constraints
0 ≤ len(segments) ≤ 2000-10^6 ≤ l ≤ r ≤ 10^6for each segment0 ≤ d ≤ 10^6- Segments may overlap, be nested, or be identical.
landrare integers, but optimal guard positions may be non-integers (your algorithm only needs to return the count).
Examples
Example 1
Input: min_guards([[1, 5], [8, 10]], 3)
Output: 2
Example 2
Input: min_guards([[0, 0], [5, 5], [10, 10]], 0)
Output: 3
Example 3
Input: min_guards([[2, 14]], 3)
Output: 2
Hints
Hint 1
Sort segments by right endpoint (and break ties by left endpoint). Process them left-to-right: the 'hardest' constraint at each step is the segment whose right end comes soonest.
Hint 2
For the current uncovered leftmost point, a guard must be placed no later than (leftmost_uncovered + d) to reach it, and that guard then covers up to (leftmost_uncovered + 2d). Use this to advance your 'covered up to' pointer greedily.
Hint 3
After placing a guard optimally, some later segments may already be fully covered — skip them. Only restart when you encounter a segment whose left endpoint exceeds your current coverage boundary.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Problem Restatement
We have a set of closed real segments on the number line that must be fully covered (every real point in every segment must lie within some guard's interval). Each guard placed at position p covers [p - d, p + d]. Minimize the number of guards.
Key Observations
-
Merge overlapping demand segments first. Two input segments that overlap or share an endpoint create a single contiguous region of demand. Merging them up-front simplifies the sweep: we then have a set of disjoint demand intervals, and each must be fully covered independently (a guard placed to serve one disjoint block cannot help another).
-
Greedy exchange argument (sweep line). Within a single merged demand interval
[L, R], we sweep left-to-right. Letposbe the leftmost uncovered real point (initiallyL). We must place a guard that reachespos; delaying it further right only risks leavingposuncovered. The optimal placement is the rightmost position that still coverspos: guard atpos + d, which covers[pos, pos + 2d]. This is the canonical greedy exchange: any other valid placement for this guard covers strictly less of the remaining segment, so it cannot require fewer total guards. -
Advance and repeat. After placing the guard,
covered_right = pos + 2d. Ifcovered_right ≥ R, we are done with this interval; otherwise we setpos = covered_rightand repeat. Becaused > 0,posstrictly increases each iteration, guaranteeing termination. -
Special case
d = 0. A guard covers a single real point. Covering a non-degenerate segment[l, r]withl < rwould require uncountably many guards → return-1. A degenerate segment[l, l](a single point) needs exactly 1 guard.
Correctness
- Merging is safe: guards covering one merged block never help a disjoint block (real line, not wrap-around).
- Greedy is optimal: by the standard exchange argument, replacing the leftmost guard with any position ≤
pos + dcan only cover the same or less of the suffix; replacing with a position >pos + dfails to coverpos. Hence the greedy choice is uniquely optimal for each step. - For a demand segment of length
W = R - L, the number of guards placed is⌈W / (2d)⌉, which is the theoretical minimum (each guard contributes exactly2dof new coverage along the sweep direction).
Complexity
- Time: O(n log n) for sorting + O(n) for merging + O(n + G) for the sweep, where G is the total number of guards placed. In the worst case G = O(n · max_length / d), but for typical inputs it is small.
- Space: O(n) for the merged list.
Reference Solution
from typing import List
def min_guards(segments: List[List[int]], d: int) -> int:
if not segments:
return 0
# Step 1: merge overlapping / touching demand segments
sorted_segs = sorted(segments, key=lambda s: (s[0], s[1]))
merged: List[List[int]] = []
for l, r in sorted_segs:
if merged and l <= merged[-1][1]:
merged[-1][1] = max(merged[-1][1], r)
else:
merged.append([l, r])
guards = 0
for seg_l, seg_r in merged:
if d == 0:
if seg_l < seg_r:
return -1 # impossible to cover a real segment with point-guards
guards += 1 # degenerate segment: one guard at the point
continue
# Step 2: greedy sweep within this demand interval
pos = float(seg_l) # leftmost uncovered real point
while pos <= seg_r:
# place guard as far right as possible while still covering pos
covered_right = pos + 2 * d
guards += 1
if covered_right >= seg_r:
break
pos = covered_right # next uncovered point starts here (closed interval)
return guards