Fewest Irrigation Devices to Water a Linear Garden
Greedy & IntervalsAuto-graded · 20 test casesLast updated
Tests greedy interval selection and the ability to handle coverage gaps in a linear range.
You need to irrigate a garden that stretches along a straight line from coordinate 0 to coordinate L. You have access to n irrigation devices. Device i is positioned at coordinate p[i] and waters everything within distance r[i] of its location, covering the segment [p[i] - r[i], p[i] + r[i]].
Determine the smallest number of devices you must activate so that every point in the segment [0, L] receives water. If complete coverage is impossible, return -1.
Write a function that takes the garden length L, a list of device positions p, and a list of device ranges r, then returns the minimum count of devices needed.
Constraints
0 ≤ L ≤ 10⁶1 ≤ n ≤ 10⁵-10⁶ ≤ p[i] ≤ 10⁶0 ≤ r[i] ≤ 10⁶- Positions and ranges may be floating-point numbers
- Intervals are closed: a device ending at coordinate
xand another starting atxconnect without a gap
Examples
Example 1
Input: min_irrigation_devices(10, [1, 3, 5, 8], [2, 2, 2, 2])
Output: 3
Example 2
Input: min_irrigation_devices(5, [1, 2], [0.5, 0.5])
Output: -1
Hints
Hint 1
Convert each device into an interval and clip it to the garden boundaries [0, L]. Coverage outside the target range doesn't help.
Hint 2
Sort intervals by their starting coordinate, then use a greedy sweep: at each step, among all intervals that touch or overlap your current coverage, pick the one extending farthest to the right.
Hint 3
If at any point no interval can extend your covered region forward, a gap exists and the garden cannot be fully watered.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem is a classic interval coverage task solved with a greedy algorithm.
Step 1: Build and clip intervals. Each device covers [p[i] - r[i], p[i] + r[i]]. Clip these intervals to [0, L] because coverage outside the garden is irrelevant. Discard any interval that becomes invalid after clipping (where the right endpoint falls below the left).
Step 2: Sort intervals. Order them by their left endpoint. This allows us to scan from left to right.
Step 3: Greedy sweep. Maintain a variable covered representing the rightmost point we have watered so far, starting at 0. In each round:
- Examine every interval whose left endpoint is at or before
covered. These intervals can extend coverage without creating a gap. - Among these candidates, select the one with the farthest right endpoint.
- Update
coveredto this new right endpoint and increment the device count.
Step 4: Detect gaps. If no interval can push covered forward, there is an uncovered gap between covered and L, so return -1. If we successfully reach or exceed L, return the device count.
Why this works: The greedy choice is optimal. At each step, choosing the interval that reaches farthest to the right maximizes our progress. Any other choice would leave us at the same position or worse, potentially requiring an additional device later. The problem has optimal substructure: after extending coverage to a new point, the remaining task is identical in form.
Because intervals are closed, two intervals touching at a single coordinate (one ending at x, another starting at x) connect seamlessly with no gap. This is why we use intervals[index][0] <= covered rather than a strict inequality.
Complexity:
- Time: O(n log n) for sorting the intervals. The sweep itself is O(n) because the
indexpointer advances through the list exactly once. - Space: O(n) to store the clipped intervals.
Solution Code
from typing import List
def min_irrigation_devices(L: float, p: List[float], r: List[float]) -> int:
if L <= 0:
return 0
intervals = []
for position, radius in zip(p, r):
left = max(0.0, position - radius)
right = min(float(L), position + radius)
if right >= 0.0 and left <= float(L) and right >= left:
intervals.append((left, right))
intervals.sort()
covered = 0.0
index = 0
used = 0
n = len(intervals)
while covered < L:
farthest = covered
while index < n and intervals[index][0] <= covered:
farthest = max(farthest, intervals[index][1])
index += 1
if farthest <= covered:
return -1
covered = farthest
used += 1
return used