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^6
  • 1 <= n <= 10^5, where n == len(p) == len(r)
  • -10^6 <= p[i] <= 10^6
  • 0 <= r[i] <= 10^6
  • L, p[i], and r[i] may be integers or floating-point numbers.

Step-by-step walkthrough

  1. Understand the goal and coverage rules

    We have a 1D garden path stretching along a number line from 0 to L. Each sprinkler i sits at coordinate p[i] with radius r[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 -1 if 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 in 0..10 yet 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 point 4 and combine into [-2, 10].
    • Spray outside [0, L] is harmless. A sprinkler can extend left of 0 or right of L, or sit completely outside the target strip (in which case it never helps).
    • When L = 0, the path is the single point 0. At least one sprinkler must still cover 0 (start <= 0 <= end), giving 1 if possible and -1 otherwise.
    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!
    
  2. Why brute force is too slow

    A straightforward brute-force approach checks every subset of 1 sprinkler, then 2 sprinklers, 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^n checks. That works fine as a test oracle for n <= 8, where 2^8 = 256, but here n can be 100,000. We need a way to pick one sprinkler after another from left to right without ever needing to backtrack.

  3. 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, and covered_until < L. Consider the dry ground immediately to the right of covered_until:

    1. The next sprinkler we pick must have start <= covered_until. If every remaining sprinkler started strictly after covered_until, a tiny strip right after covered_until would stay dry forever.
    2. Among all sprinklers with start <= covered_until, we should pick the one with the largest end. Why is that always safe? Any valid solution has to pick some sprinkler C with start_C <= covered_until to cover the points just past covered_until. Everything to the left of covered_until is already wet, so only how far right C reaches matters for the rest of the path. Swapping C for the farthest-reaching candidate G covers every point C covered 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
    
  4. Step 1: build and sort the intervals

    If we sort all intervals by start from smallest to largest, then at any moment the intervals satisfying start <= covered_until sit at the front of the remaining list. Better yet, because covered_until only moves right as we add sprinklers, a single index scan_idx can 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 whether start <= covered_until and whether end >= 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()
    
  5. Step 2: water point `0` first

    The very first sprinkler has a specific job: it must cover point 0. That means start <= 0 and end >= 0 (for example, [-5, -2] has start <= 0 but stops before the path even begins!).

    We advance scan_idx across every interval with start <= 0 and record the maximum end in farthest_end. If no interval qualifies, or the best farthest_end is still negative, point 0 cannot be watered and we immediately return -1. Otherwise we have used 1 sprinkler 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_end
    
  6. Step 3: extend coverage until `covered_until >= L`

    While covered_until < L, we run one greedy round per additional sprinkler:

    1. Initialize farthest_end = covered_until.
    2. Advance scan_idx through all newly reachable intervals with start <= covered_until, updating farthest_end whenever an interval reaches farther right.
    3. If farthest_end == covered_until after scanning all candidates, no sprinkler reaches past covered_until. There is a dry gap right after covered_until, so return -1.
    4. Otherwise, increment sprinklers_used and move covered_until to farthest_end.

    Why do we never need to re-check intervals from earlier rounds? Every interval scanned in an earlier round had end at most equal to our current covered_until, so none of them can push past covered_until now.

        # 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
    
  7. 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 returns 3. Notice [1, 5] was scanned and skipped in Round 1 because [4, 10] touched 4 and reached farther right.

  8. 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 the n intervals takes O(n) time, sorting them by start takes O(n log n) time, and the greedy sweep takes O(n) total time because scan_idx only moves forward and inspects each interval at most once across all rounds.
  • Space: O(n). We store up to n (start, end) tuples in intervals (and Python's Timsort uses up to O(n) temporary space while sorting).

Edge cases

  • Single sprinkler covers the entire path: Phase 2 sets covered_until >= L on the first pick, the while covered_until < L loop never runs, and we return 1.
  • Intervals touching at a single point: Closed intervals (intervals that include both endpoints) like [-2, 4] and [4, 10] share the point 4 and leave zero dry gap, which intervals[scan_idx][0] <= covered_until accepts.
  • Dry gap at the start, middle, or end: Point 0 uncovered (farthest_end is None or farthest_end < 0), a middle gap (farthest_end == covered_until, as in Example 2), or running out of intervals before L all return -1.
  • Zero-radius sprinklers (r[i] = 0): [p, p] waters a single point. It cannot advance covered_until across any positive distance, so it only ever helps when L = 0 and p = 0.
  • Zero-length path (L = 0): [0, 0] is the single coordinate 0, returning 1 if at least one sprinkler covers 0 and -1 otherwise.
  • Sprinklers extending outside [0, L]: Intervals like [-8, -2] end before 0 (farthest_end < 0 rejects them unless another interval covers 0), and intervals starting past L are never needed once covered_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: Writing intervals[scan_idx][0] < covered_until rejects touching closed intervals such as [-2, 4] and [4, 10], failing Example 1.
  • Taking the first interval that extends covered_until instead of the maximum: Stopping the inner scan as soon as candidate_end > covered_until can pick [1, 5] before even seeing [4, 10], using more sprinklers than needed.
  • Forgetting farthest_end < 0 on the first pick: An interval like [-5, -2] satisfies start <= 0 yet stops left of 0, leaving point 0 dry.
  • Infinite loop on a gap: If no interval with start <= covered_until has end > covered_until, covered_until never grows; checking farthest_end == covered_until is essential to break out and return -1.

Alternative approaches

  • Jump-game reach array (integer coordinates only): When L is modest and all endpoints are integers, clip intervals to [0, L], record max_reach[s] = max end for every integer start s, and sweep 0..L in O(n + L) time without sorting. Because p[i] and r[i] here are floats (like 1.5 in Example 2), sorting intervals is cleaner and handles arbitrary real numbers.
  • Breadth-first search (BFS) on intervals: Treat intervals covering 0 as starting nodes and add an edge from interval A to interval B whenever start_B <= end_A, then run BFS (a level-by-level graph search that finds shortest paths in unweighted graphs) to reach end >= L. Correct, but up to O(n^2) edges make it too slow for n = 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 n intervals dominates at O(n log n) time, while the greedy sweep afterward takes O(n) time because scan_idx increments at most n times across the entire run. Together that gives O(n log n) total time and O(n) space to store the interval tuples, compared to O(n^2) worst-case time if you skip sorting and rescan all n sprinklers 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 by end; let dp[j] be the minimum cost to cover [0, end_j] ending with interval j, equal to cost[j] when start_j == 0 and cost[j] + min(dp[i] for end_i >= start_j) otherwise, then take min(dp[j] for end_j == L). Evaluating that range minimum directly takes O(n^2) time, or O(n log n) with a segment tree (a binary tree over an array that answers range-minimum queries and point updates in O(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) + 1 approximation across M cells.

Follow-up questions

Similar questions

More Quince interview questions

All 2 Quince questions →