Minimum Number of Taps to Open to Water a Garden solution explained

To find the minimum number of taps that water a garden, convert every tap into the segment it waters, clipped to the garden, and record for each left endpoint the farthest right end that starts there. Then sweep from 0 to n like the jump game: each time you reach the edge of the watered part, open one more tap that reaches as far as possible, or return -1 if nothing reaches past it. The sweep is O(n) time and O(n) space.

By Published 8 min read

The problem in plain words

A strip of lawn runs from position 0 to position n. There is a sprinkler at every whole-number position, so n + 1 of them. You are given an array where entry i says how far sprinkler i sprays in each direction: if it is r, sprinkler i wets everything from i - r to i + r. Spray that goes past either end of the lawn is wasted but harmless. Choose the fewest sprinklers to turn on so that every part of the lawn, including the bits between whole-number positions, gets wet. If the lawn cannot be fully watered, return -1.

Small examples, written for this page
nSpray radius per positionAnswerWhy
6[1, 0, 2, 0, 0, 2, 0]2Position 2 covers 0 to 4, position 5 covers 3 to 6
4[0, 0, 4, 0, 0]1Position 2 covers the whole lawn on its own
4[0, 0, 0, 0, 0]-1Each sprinkler only wets a single point
5[1, 1, 0, 0, 1, 1]-1Nothing wets the stretch between 2 and 3
3[1, 1, 1, 1]2Positions 1 and 2, or positions 1 and 3
Small examples, written for this page. Scroll sideways on a small screen.

The third row is the trap. Every whole-number position gets a drop of water, yet the answer is -1, because the stretch between 0 and 1 stays dry. Confirm with the interviewer that full continuous coverage is what they mean; in the usual statement it is.

The translation step

Interviewers often use this problem to see whether you recognize a known pattern behind new wording. Once each sprinkler is written as a segment, the sprinklers stop mattering. You have a set of segments on a line and want the fewest that cover [0, n]. Clip each one to the lawn, because a segment that starts at -3 is no better than one that starts at 0, and a segment ending at n + 4 is no better than one ending at n.

Many segments can start at the same left point. Only the one that reaches farthest right matters, since any cover that uses a shorter one could use the longer one instead. So compress everything into one array, jump, where jump[x] is the farthest right end among segments that start at x. That array has n + 1 slots and takes one pass over the radii to fill.

Slow approach: relax segments in order of their left end

A DP gives a clear correctness story. Let cost[x] be the fewest sprinklers whose combined spray covers [0, x], with cost[0] = 0. Sort the segments by left end. For a segment [lo, hi], if [0, lo] can be covered, then every point x between lo and hi can be covered with one more sprinkler, so cost[x] is at most cost[lo] + 1. Processing segments by left end guarantees cost[lo] is already final when you use it, because only segments starting further left can improve it. The cost is O(n · w) where w is the widest segment, so up to O(n²).

def fewest_taps_slow(n, ranges):
    INF = float("inf")
    cost = [0] + [INF] * n  # cost[x]: sprinklers needed to wet [0, x]
    spans = sorted((max(0, i - r), min(n, i + r)) for i, r in enumerate(ranges))
    for lo, hi in spans:
        if cost[lo] == INF:
            continue
        for x in range(lo + 1, hi + 1):
            cost[x] = min(cost[x], cost[lo] + 1)
    return -1 if cost[n] == INF else cost[n]
Python, up to O(n²): a DP over positions.

Main approach: one sweep over the jump array

Walk x from 0 up to n - 1 with three numbers: taps opened so far, wet_to (how far the opened taps already reach) and best (the farthest any segment starting at or before x could reach). At each x, update best with jump[x]. When x catches up with wet_to, the opened taps are about to run out, so you must open another. If best is not beyond x, there is a dry patch right after x and the answer is -1. Otherwise count a tap and set wet_to to best. Once wet_to reaches n, the remaining steps never trigger another tap.

Why does choosing the farthest reach work? At the moment you must open a tap, any tap you could open starts no later than x. Among them, the one that reaches farthest leaves every future option open and closes none, so no other choice can lead to fewer taps overall.

def fewest_taps(n, ranges):
    jump = [0] * (n + 1)  # farthest right end of a spray that starts at x
    for i, r in enumerate(ranges):
        left = max(0, i - r)
        jump[left] = max(jump[left], min(n, i + r))
    taps = wet_to = best = 0
    for x in range(n):
        best = max(best, jump[x])
        if x == wet_to:
            if best <= x:
                return -1  # dry patch just after x
            taps += 1
            wet_to = best
    return taps
Python: O(n) time, O(n) extra space.
function fewestTaps(n, ranges) {
  const jump = new Array(n + 1).fill(0);
  ranges.forEach((r, i) => {
    const left = Math.max(0, i - r);
    jump[left] = Math.max(jump[left], Math.min(n, i + r));
  });
  let taps = 0, wetTo = 0, best = 0;
  for (let x = 0; x < n; x++) {
    best = Math.max(best, jump[x]);
    if (x === wetTo) {
      if (best <= x) return -1;
      taps++;
      wetTo = best;
    }
  }
  return taps;
}
JavaScript: the same sweep.

Trace of the first example

With n = 6 and radii [1, 0, 2, 0, 0, 2, 0], the segments are [0, 1], [1, 1], [0, 4], [3, 3], [4, 4], [3, 6] and [6, 6]. The jump array becomes [4, 1, 0, 6, 4, 0, 6]: slot 0 keeps the larger of 1 and 4, slot 3 keeps 6. At x = 0, best is 4 and wet_to is 0, so the first tap opens and wet_to becomes 4. At x = 3, best rises to 6. At x = 4, x equals wet_to, best is 6, so a second tap opens and wet_to becomes 6. The loop ends with 2 taps.

Complexity

Running cost of each idea
IdeaTimeExtra space
Try every subset of sprinklersO(2ⁿ · n)O(n)
DP relaxing segments by left endO(n log n + n · w), up to O(n²)O(n)
Jump array plus greedy sweepO(n)O(n)
Running cost of each idea. Scroll sideways on a small screen.

Because every tap position is a whole number from 0 to n, the jump array never needs more than n + 1 slots and no sort is required. That is what makes this version linear, unlike interval problems where the endpoints can be arbitrary.

Edge cases to test

  • All radii zero with n at least 1: the answer is -1.
  • One sprinkler with a huge radius in the middle: the answer is 1.
  • A radius larger than the lawn on the first or last sprinkler: clipping must handle negative left ends and right ends past n.
  • A dry gap between two groups of sprinklers: the sweep must stop with -1 rather than skip the gap.
  • n = 0: the lawn is a single point, so ask what to return; the code here returns 0.
  • Several sprinklers whose segments share a left end: only the longest should be kept.

Mistakes that cost points

  • Checking only whole-number positions, which accepts the all-zero case wrongly.
  • Forgetting to clip i - r at 0, which writes to a negative index. In Python that silently updates the wrong slot from the end of the array.
  • Storing every segment per left end instead of only the longest, which wastes memory and complicates the sweep.
  • Looping x up to and including n, then opening a pointless extra tap at the end.
  • Opening a tap at every position where best grows, instead of only when the watered stretch runs out.
  • Saying the solution is O(n log n) when no sort is involved. Know your own complexity.

How to explain it out loud

Fictional example

Talking an interviewer through the reduction
Candidate
First I turn each sprinkler into the segment it wets, clipped to the lawn. Now it is the classic question of covering a line with the fewest segments.
Candidate
For each left end I only keep the longest reach, in an array of size n plus one. Then I sweep like the jump game: when I hit the end of what is already wet, I open the tap that reaches farthest from anything starting at or before here.
Candidate
If that farthest reach does not pass my position, there is a dry patch and I return -1. It is one pass, so O(n) time and O(n) space.

Other problems in this set

Video Stitching is the same covering task with the segments handed to you directly, which makes it a good second rep. For a greedy built on sorting by a difference rather than by position, move on to Two City Scheduling. More array and greedy topics are collected in the data structure interview questions.

Practice it with Natively

While you practice, Natively can read a problem like this from a screenshot and suggest how to reframe it, for example as interval covering, so you can check your own reduction against it once you have had a go. It keeps a transcript of your mock interview on your machine too, which shows whether you mentioned the all-zero trap and the clipping step. See how an AI interview assistant works on Mac and Windows.

Questions people ask

How do you solve Minimum Number of Taps to Open to Water a Garden?

Turn tap i into the segment from max(0, i - r) to min(n, i + r), keep the farthest right end for each left end, then sweep from 0 like the jump game, opening a tap only when the watered stretch runs out. Return -1 if no tap reaches past that point.

What is the time complexity?

O(n) time and O(n) space. Tap positions are whole numbers from 0 to n, so the farthest-reach array needs no sorting.

Why is the answer -1 when every position gets some water?

The garden must be covered continuously. A tap with radius 0 wets only its own point, so the stretch between two such points stays dry.

How is this related to Video Stitching and Jump Game II?

All three are the same covering problem. Once taps are written as segments, the fewest taps is the fewest segments covering [0, n], solved by always extending to the farthest reach.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP