Minimum Sprinklers Needed to Water a Linear Garden
Medium · Coding & Algorithms · Software Engineer · Online Assessment
Problem Statement
A straight garden path spans the closed real interval [0, L] along a number line. Alongside it sit n sprinkler heads: head i is mounted at coordinate p[i] with spray radius r[i], wetting every real point in the closed segment [p[i] - r[i], p[i] + r[i]].
Implement min_sprinklers(L, p, r) to return the fewest sprinkler heads that must be turned on so every real point in [0, L] is wet. Return -1 if no combination of heads can cover the entire path without dry gaps.
Coverage follows continuous real-line geometry:
- Endpoints are inclusive, so two segments that meet at a single coordinate (such as [-2, 4] and [4, 10]) leave no dry gap at 4.
- Spray reaching left of 0 or right of L is permitted.
- If L = 0, the path reduces to the single coordinate 0, which still requires at least one head whose segment contains 0.
Examples
Example 1
Input: L = 12, p = [1, 3, 7, 10], r = [3, 2, 3, 3]
Output: 3
The four heads cover [-2, 4], [1, 5], [4, 10], and [7, 13]. Turning on [-2, 4], [4, 10], and [7, 13] wets [-2, 13], continuously covering [0, 12] with 3 heads (skipping [1, 5]).
Example 2
Input: L = 8, p = [1.5, 6.5], r = [1.5, 2.0]
Output: -1
The two heads cover [0.0, 3.0] and [4.5, 8.5]. Although both ends 0 and 8 are wet, the open stretch (3.0, 4.5) stays dry, so covering [0, 8] is impossible.
Constraints
0 <= L <= 10^61 <= n <= 10^5, wheren == len(p) == len(r)-10^6 <= p[i] <= 10^60 <= r[i] <= 10^6L,p[i], andr[i]may be integers or floating-point numbers.
Step-by-step walkthrough
Understand the goal and coverage rules
We have a 1D garden path stretching along a number line from
0toL. Each sprinklerisits at coordinatep[i]with radiusr[i]and waters the closed interval[p[i] - r[i], p[i] + r[i]](a closed interval includes both of its endpoints). We want the smallest number of sprinklers whose intervals together cover every real point in[0, L], or-1if some part of the path cannot be reached.Before writing code, notice four important details about the geometry:
- Coverage is continuous, not just at integer coordinates. Positions and radii can be decimals like
1.5. Even with integers,[0, 4]and[5, 10]water every integer in0..10yet leave the open stretch(4, 5)dry, so the answer is-1. - Touching endpoints leave no gap. Because intervals include their endpoints,
[-2, 4]and[4, 10]share the point4and combine into[-2, 10]. - Spray outside
[0, L]is harmless. A sprinkler can extend left of0or right ofL, or sit completely outside the target strip (in which case it never helps). - When
L = 0, the path is the single point0. At least one sprinkler must still cover0(start <= 0 <= end), giving1if possible and-1otherwise.
Touching at 4 (valid cover of [0, 10]): [-2, 4]: |===========| [4, 10]: |===========| garden : 0-------4-----------10 Gap between 3.0 and 4.5 (fails to cover [0, 8]): [0.0, 3.0]: |=======| [4.5, 8.5]: |=========| garden : 0-------3 4.5-------8 ^^^ dry!- Coverage is continuous, not just at integer coordinates. Positions and radii can be decimals like
Why brute force is too slow
A straightforward brute-force approach checks every subset of
1sprinkler, then2sprinklers, and so on, merging each subset's intervals to see whether[0, L]falls inside one merged block.Trying all subsets takes up to
2^nchecks. That works fine as a test oracle forn <= 8, where2^8 = 256, but herencan be100,000. We need a way to pick one sprinkler after another from left to right without ever needing to backtrack.Greedy insight: always take the farthest right reach
A greedy algorithm makes the single best-looking choice at each step and never reconsiders earlier picks. Let's see why a left-to-right greedy rule gives the exact minimum here.
Suppose we have already watered
[0, covered_until]without gaps, andcovered_until < L. Consider the dry ground immediately to the right ofcovered_until:- The next sprinkler we pick must have
start <= covered_until. If every remaining sprinkler started strictly aftercovered_until, a tiny strip right aftercovered_untilwould stay dry forever. - Among all sprinklers with
start <= covered_until, we should pick the one with the largestend. Why is that always safe? Any valid solution has to pick some sprinklerCwithstart_C <= covered_untilto cover the points just pastcovered_until. Everything to the left ofcovered_untilis already wet, so only how far rightCreaches matters for the rest of the path. SwappingCfor the farthest-reaching candidateGcovers every pointCcovered and possibly more, using the exact same number of sprinklers.
Already wet: [0, 4] (covered_until = 4) Candidates with start <= 4: A: [1, 5] |======| B: [2, 4] |====| G: [4, 10] |==========| <-- reaches 10 (farthest right), always best! garden: 0--1-2---4-5-------10--12- The next sprinkler we pick must have
Step 1: build and sort the intervals
If we sort all intervals by
startfrom smallest to largest, then at any moment the intervals satisfyingstart <= covered_untilsit at the front of the remaining list. Better yet, becausecovered_untilonly moves right as we add sprinklers, a single indexscan_idxcan walk forward through the sorted list once across the entire function.We do not even need to clip intervals to
[0, L]: our comparisons only check whetherstart <= covered_untiland whetherend >= L, so overhanging ends never confuse the logic.# Phase 1: Convert each sprinkler into its closed coverage interval (start, end). # intervals: list of (start, end) float pairs, e.g. [(-2.0, 4.0), (1.0, 5.0)] intervals: List[Tuple[float, float]] = [] for idx in range(len(p)): start = p[idx] - r[idx] end = p[idx] + r[idx] # Guard against negative r[idx], which would represent an empty interval (start > end). if start <= end: intervals.append((start, end)) # Sort by start position ascending (ties broken by end) so all intervals # starting at or before our current watered boundary form a contiguous prefix. intervals.sort()Step 2: water point `0` first
The very first sprinkler has a specific job: it must cover point
0. That meansstart <= 0andend >= 0(for example,[-5, -2]hasstart <= 0but stops before the path even begins!).We advance
scan_idxacross every interval withstart <= 0and record the maximumendinfarthest_end. If no interval qualifies, or the bestfarthest_endis still negative, point0cannot be watered and we immediately return-1. Otherwise we have used1sprinkler and watered[0, farthest_end].num_intervals = len(intervals) # scan_idx: forward-only cursor into sorted `intervals`; each interval is visited at most once. scan_idx = 0 # Phase 2: Pick the first sprinkler to cover point 0. # It must start at or left of 0 (start <= 0) and reach at least 0 (end >= 0); # among all such candidates, greedily choose the one reaching farthest right. farthest_end: Optional[float] = None while scan_idx < num_intervals and intervals[scan_idx][0] <= 0: candidate_end = intervals[scan_idx][1] if farthest_end is None or candidate_end > farthest_end: farthest_end = candidate_end scan_idx += 1 # If nothing starts <= 0, or every such sprinkler ends strictly before 0, point 0 stays dry. if farthest_end is None or farthest_end < 0: return -1 sprinklers_used = 1 # covered_until: rightmost point continuously watered from 0, so [0, covered_until] is wet. covered_until = farthest_endStep 3: extend coverage until `covered_until >= L`
While
covered_until < L, we run one greedy round per additional sprinkler:- Initialize
farthest_end = covered_until. - Advance
scan_idxthrough all newly reachable intervals withstart <= covered_until, updatingfarthest_endwhenever an interval reaches farther right. - If
farthest_end == covered_untilafter scanning all candidates, no sprinkler reaches pastcovered_until. There is a dry gap right aftercovered_until, so return-1. - Otherwise, increment
sprinklers_usedand movecovered_untiltofarthest_end.
Why do we never need to re-check intervals from earlier rounds? Every interval scanned in an earlier round had
endat most equal to our currentcovered_until, so none of them can push pastcovered_untilnow.# Phase 3: Repeatedly extend [0, covered_until] until covered_until >= L. while covered_until < L: farthest_end = covered_until # Use <= (not <) because closed intervals that touch at covered_until # (such as [-2, 4] and [4, 10]) share that boundary point and leave no dry gap. while scan_idx < num_intervals and intervals[scan_idx][0] <= covered_until: candidate_end = intervals[scan_idx][1] if candidate_end > farthest_end: farthest_end = candidate_end scan_idx += 1 # If no candidate reaches past covered_until, the points just right of it cannot be watered. if farthest_end == covered_until: return -1 sprinklers_used += 1 covered_until = farthest_end return sprinklers_used- Initialize
Trace Example 1 step by step
Let
L = 12,p = [1, 3, 7, 10],r = [3, 2, 3, 3].Sorted intervals: idx 0: (-2, 4) idx 1: ( 1, 5) idx 2: ( 4, 10) idx 3: ( 7, 13) Phase 2 (cover point 0, scan start <= 0): scan_idx=0 -> (-2, 4) has start -2 <= 0 -> farthest_end = 4 scan_idx=1 -> ( 1, 5) has start 1 > 0 -> stop inner scan sprinklers_used = 1, covered_until = 4 (wet: [0, 4]) Phase 3, Round 1 (covered_until = 4 < 12, scan start <= 4): scan_idx=1 -> ( 1, 5) has start 1 <= 4 -> farthest_end = 5 scan_idx=2 -> ( 4, 10) has start 4 <= 4 -> farthest_end = 10 scan_idx=3 -> ( 7, 13) has start 7 > 4 -> stop inner scan sprinklers_used = 2, covered_until = 10 (wet: [0, 10]) Phase 3, Round 2 (covered_until = 10 < 12, scan start <= 10): scan_idx=3 -> ( 7, 13) has start 7 <= 10 -> farthest_end = 13 scan_idx=4 -> end of list sprinklers_used = 3, covered_until = 13 (wet: [0, 13], covers [0, 12]!)covered_until >= 12, so the loop finishes and returns3. Notice[1, 5]was scanned and skipped in Round 1 because[4, 10]touched4and reached farther right.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def min_sprinklers(L: float, p: List[float], r: List[float]) -> int: # Phase 1: Convert each sprinkler into its closed coverage interval (start, end). # intervals: list of (start, end) float pairs, e.g. [(-2.0, 4.0), (1.0, 5.0)] intervals: List[Tuple[float, float]] = [] for idx in range(len(p)): start = p[idx] - r[idx] end = p[idx] + r[idx] # Guard against negative r[idx], which would represent an empty interval (start > end). if start <= end: intervals.append((start, end)) # Sort by start position ascending (ties broken by end) so all intervals # starting at or before our current watered boundary form a contiguous prefix. intervals.sort() num_intervals = len(intervals) # scan_idx: forward-only cursor into sorted `intervals`; each interval is visited at most once. scan_idx = 0 # Phase 2: Pick the first sprinkler to cover point 0. # It must start at or left of 0 (start <= 0) and reach at least 0 (end >= 0); # among all such candidates, greedily choose the one reaching farthest right. farthest_end: Optional[float] = None while scan_idx < num_intervals and intervals[scan_idx][0] <= 0: candidate_end = intervals[scan_idx][1] if farthest_end is None or candidate_end > farthest_end: farthest_end = candidate_end scan_idx += 1 # If nothing starts <= 0, or every such sprinkler ends strictly before 0, point 0 stays dry. if farthest_end is None or farthest_end < 0: return -1 sprinklers_used = 1 # covered_until: rightmost point continuously watered from 0, so [0, covered_until] is wet. covered_until = farthest_end # Phase 3: Repeatedly extend [0, covered_until] until covered_until >= L. while covered_until < L: farthest_end = covered_until # Use <= (not <) because closed intervals that touch at covered_until # (such as [-2, 4] and [4, 10]) share that boundary point and leave no dry gap. while scan_idx < num_intervals and intervals[scan_idx][0] <= covered_until: candidate_end = intervals[scan_idx][1] if candidate_end > farthest_end: farthest_end = candidate_end scan_idx += 1 # If no candidate reaches past covered_until, the points just right of it cannot be watered. if farthest_end == covered_until: return -1 sprinklers_used += 1 covered_until = farthest_end return sprinklers_used✅ Submit now — all tests should pass.
Intuition & how it works
Imagine laying wooden planks end-to-end across a muddy path from 0 to L using as few planks as possible, where each plank can only sit in one fixed spot [p[i] - r[i], p[i] + r[i]]. Your first plank has to cover the starting line 0, and if several planks cover 0, you naturally pick the one that reaches farthest forward. From the end of that plank, you look at every plank that touches or overlaps your dry-foot boundary and again step onto whichever one reaches farthest toward L. This step-by-step "always push the watered frontier as far right as possible" strategy is a greedy algorithm (an algorithm that makes the best local choice at each step without undoing earlier picks).
Trying every combination of sprinklers to find the smallest valid subset takes O(2^n) time, which explodes long before n = 100,000. Simple shortcuts like picking the widest sprinklers first also fail: a huge sprinkler in the middle is useless if 0 is still dry, and taking the first overlapping sprinkler you see instead of the farthest-reaching one wastes sprinklers on tiny steps. Sorting intervals by start and greedily jumping to the maximum end among all intervals with start <= covered_until avoids both traps in a single pass.
Walk through Example 1 (L = 12) with sorted intervals [-2, 4], [1, 5], [4, 10], [7, 13]:
1. Cover 0: Only [-2, 4] has start <= 0, so we pick it (sprinklers_used = 1, covered_until = 4).
2. Extend from 4: Both [1, 5] and [4, 10] satisfy start <= 4; [4, 10] reaches farther (10 > 5), so we pick [4, 10] (sprinklers_used = 2, covered_until = 10).
3. Extend from 10: [7, 13] satisfies start <= 10 and pushes covered_until to 13 >= L, finishing with 3 sprinklers.
Complexity
- Time:
O(n log n). Building thenintervals takesO(n)time, sorting them bystarttakesO(n log n)time, and the greedy sweep takesO(n)total time becausescan_idxonly moves forward and inspects each interval at most once across all rounds. - Space:
O(n). We store up ton(start, end)tuples inintervals(and Python's Timsort uses up toO(n)temporary space while sorting).
Edge cases
- Single sprinkler covers the entire path: Phase 2 sets
covered_until >= Lon the first pick, thewhile covered_until < Lloop never runs, and we return1. - Intervals touching at a single point: Closed intervals (intervals that include both endpoints) like
[-2, 4]and[4, 10]share the point4and leave zero dry gap, whichintervals[scan_idx][0] <= covered_untilaccepts. - Dry gap at the start, middle, or end: Point
0uncovered (farthest_end is None or farthest_end < 0), a middle gap (farthest_end == covered_until, as in Example 2), or running out of intervals beforeLall return-1. - Zero-radius sprinklers (
r[i] = 0):[p, p]waters a single point. It cannot advancecovered_untilacross any positive distance, so it only ever helps whenL = 0andp = 0. - Zero-length path (
L = 0):[0, 0]is the single coordinate0, returning1if at least one sprinkler covers0and-1otherwise. - Sprinklers extending outside
[0, L]: Intervals like[-8, -2]end before0(farthest_end < 0rejects them unless another interval covers0), and intervals starting pastLare never needed oncecovered_until >= L.
Common mistakes
- Checking only integer coordinates: Treating
[0, 4]and[5, 10]as adjacent leaves the continuous segment(4, 5)unwatered; on a continuous real segment the answer is-1. - Using
<instead of<=when checking overlap: Writingintervals[scan_idx][0] < covered_untilrejects touching closed intervals such as[-2, 4]and[4, 10], failing Example 1. - Taking the first interval that extends
covered_untilinstead of the maximum: Stopping the inner scan as soon ascandidate_end > covered_untilcan pick[1, 5]before even seeing[4, 10], using more sprinklers than needed. - Forgetting
farthest_end < 0on the first pick: An interval like[-5, -2]satisfiesstart <= 0yet stops left of0, leaving point0dry. - Infinite loop on a gap: If no interval with
start <= covered_untilhasend > covered_until,covered_untilnever grows; checkingfarthest_end == covered_untilis essential to break out and return-1.
Alternative approaches
- Jump-game reach array (integer coordinates only): When
Lis modest and all endpoints are integers, clip intervals to[0, L], recordmax_reach[s] = max endfor every integer starts, and sweep0..LinO(n + L)time without sorting. Becausep[i]andr[i]here are floats (like1.5in Example 2), sorting intervals is cleaner and handles arbitrary real numbers. - Breadth-first search (BFS) on intervals: Treat intervals covering
0as starting nodes and add an edge from intervalAto intervalBwheneverstart_B <= end_A, then run BFS (a level-by-level graph search that finds shortest paths in unweighted graphs) to reachend >= L. Correct, but up toO(n^2)edges make it too slow forn = 10^5.
Follow-up questions
- Once the coverage intervals are sorted, what are the overall time and space complexities of the greedy pass? Sorting the
nintervals dominates atO(n log n)time, while the greedy sweep afterward takesO(n)time becausescan_idxincrements at mostntimes across the entire run. Together that givesO(n log n)total time andO(n)space to store the interval tuples, compared toO(n^2)worst-case time if you skip sorting and rescan allnsprinklers in every round. - Suppose each sprinkler carries an activation cost and you want the cheapest valid cover rather than the fewest sprinklers—how would your approach change? Greedy breaks because two cheap narrow sprinklers can cost less than one expensive wide sprinkler, so we switch to dynamic programming (solving a problem by combining cached answers to smaller overlapping subproblems), assuming non-negative costs. Clip every interval to
[0, L](dropping intervals completely outside[0, L]) and sort byend; letdp[j]be the minimum cost to cover[0, end_j]ending with intervalj, equal tocost[j]whenstart_j == 0andcost[j] + min(dp[i] for end_i >= start_j)otherwise, then takemin(dp[j] for end_j == L). Evaluating that range minimum directly takesO(n^2)time, orO(n log n)with a segment tree (a binary tree over an array that answers range-minimum queries and point updates inO(log n)time). - If the region to water were a 2D rectangle instead of a 1D segment, how would the problem's tractability and supporting data structures change? Each sprinkler now wets a 2D disk (or axis-aligned square), and covering a 2D rectangle with the fewest disks is NP-hard (no known polynomial-time exact algorithm exists for large inputs). In practice, you discretize the rectangle into a fine grid of sample cells, index the sprinkler shapes in an R-tree or uniform spatial grid (spatial data structures that quickly query which geometric regions overlap a 2D box), and run greedy set cover—repeatedly choosing the sprinkler that wets the most still-dry cells—giving a
ln(M) + 1approximation acrossMcells.
Follow-up questions
- Once the coverage intervals are sorted, what are the overall time and space complexities of the greedy pass?
- Suppose each sprinkler carries an activation cost and you want the cheapest valid cover rather than the fewest sprinklers—how would your approach change?
- If the region to water were a 2D rectangle instead of a 1D segment, how would the problem's tractability and supporting data structures change?
Similar questions
- Repeated Word Subsequence Check
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One