Minimum Number of Taps to Open to Water a Garden

Water a whole garden with as few taps as possible by always opening the tap that reaches furthest.

A garden lies along a straight line, from point 0 to point n. There is a tap at every whole point, n + 1 taps in all, and ranges[i] says how far tap i sprays: once opened, it waters the stretch from i - ranges[i] to i + ranges[i]. Return the smallest number of taps to open so that the whole line from 0 to n is watered, or -1 if that cannot be done.

Example 1
Input: n = 5, ranges = [3, 4, 1, 1, 0, 0]
Output: 1
Explanation: tap 1 waters from -3 to 5, which covers the whole garden.
Example 2
Input: n = 3, ranges = [0, 0, 0, 0]
Output: -1
Explanation: each tap waters only its own point, so the ground between 0 and 1 stays dry.
Example 3
Input: n = 7, ranges = [1, 2, 1, 0, 2, 1, 0, 1]
Output: 3
Explanation: taps 1, 4 and 7 water 0 to 3, 2 to 6 and 6 to 7, the end of the garden.
Solution

The Idea

Picture a long, narrow flower bed with a sprinkler at every metre mark. Some sprinklers spray far, others barely wet the soil around them. You want every bit of the bed wet, while turning on as few sprinklers as you can.

Example 2 shows what "every bit" means. Each tap there has range 0 and waters a single point, so the points 0, 1, 2 and 3 all get water, but the ground between them stays dry. Watering the garden means covering the whole line from 0 to n, with no gap anywhere.

Now take Example 3, a garden from 0 to 7. Tap 4 has range 2, so it waters from 2 to 6. Tap 7 has range 1 and would reach 8, but the part beyond 7 is outside the garden and does not count. Look at the picture below.

Example 3: the garden runs from 0 to 7, with one bar per tap showing the stretch it waters. Tap 1 covers up to 3, tap 4 then covers up to 6, and tap 7 reaches 7, so three taps are enough.

Each bar is the stretch one tap waters, and the dot inside it is the tap itself. A small ring is a tap with range 0, and the dashed box after tap 7 is the part of its spray that falls outside the garden.

Point 0 needs water, so the first tap must be one whose bar starts at 0. Tap 0 and tap 1 both do, and tap 1 reaches further, to 3. Is there any reason to prefer tap 0? No: everything tap 0 waters, tap 1 waters too. With tap 1 open, the garden is wet up to the blue line labelled "covered up to 3".

Which tap comes next? Its bar must start at 3 or earlier, or some ground just after 3 would stay dry. Tap 5 starts at 4, too late. Of the taps that start in time, tap 4 reaches furthest, to 6, which gives the line labelled "covered up to 6". From there, tap 7 starts at 6 and reaches the end, 7. The three orange bars, taps 1, 4 and 7, water the whole garden.

So the same question comes back each time: the garden is wet up to some point, and which tap, starting at or before that point, reaches furthest? Opening that tap each time the water runs out, without planning any further ahead, is called a greedy choice. It is safe here, because the tap that reaches furthest leaves no more garden to cover than any other tap that could be opened at that moment.

And when no tap that starts in time reaches past the point, the ground after it can never get water. That is what happens at point 0 in Example 2, and the answer there is -1.

Solution Approach

Trying every set of taps would work but is slow. The greedy choice needs three things instead: each tap described by where its stretch starts and ends, a quick way to find the furthest reach, and one walk along the garden that counts the taps.

Trying every set of taps

Why not try every choice of taps and keep the smallest one that waters everything? With n + 1 taps there are 2n+1 ways to choose which ones to open: 256 for the eight taps of Example 3, and over a million for twenty taps. The greedy choice opens one tap each time the water runs out, so it never compares whole sets.

Each tap as a stretch

What does the code need to know about a tap? Only the two ends of its stretch. Tap i waters from i - ranges[i] to i + ranges[i], and both ends are cut to the garden, so the left end is at least 0 and the right end at most n. In Example 1, tap 1 sprays from -3 to 5 and counts as 0 to 5.

The furthest reach from each starting point

How do we find the tap that reaches furthest without searching all taps each time? Several taps can start at the same point, like taps 0 and 1 in Example 3, which both start at 0. Only the one reaching further can ever be the best choice.

So an array named reachFrom keeps one number per point: reachFrom[x] is the furthest right end of any tap whose stretch starts at x. For Example 3 it is [3, 3, 6, 3, 6, 0, 7, 0]. Points 5 and 7 keep 0 because no stretch starts there, and 0 never beats a real reach.

Counting taps in one walk

How does that become a count? Walk a position x from 0 toward n and keep two numbers. covered is how far the taps opened so far water, and farthest is the best reach of all taps that start at or before x. When x reaches covered, the water runs out there, so one more tap opens and covered moves to farthest.

If at that moment farthest is not past x, no tap can water the ground after x, and the answer is -1. This walk also solves Jump Game II, which asks for the fewest jumps to the end of an array. Opening a tap is like jumping from where its stretch starts to where it ends.

Java Solution

The method minTaps works in these steps:

  1. First, create the array reachFrom with one cell per point, 0 to n. A loop moves i over the taps and works out tap i's stretch: left = Math.max(0, i - ranges[i]) and right = Math.min(n, i + ranges[i]). It then stores right in reachFrom[left] if that is larger than what is there.
  2. Set three counters to 0: taps, the number of taps opened; covered, the end of the watered part; and farthest, the best reach seen so far.
  3. A second loop walks x from 0 up to n - 1. At each point, farthest takes reachFrom[x] if that is larger. The loop stops before n, because a garden watered up to n needs nothing more.
  4. When x equals covered, the water runs out here. If farthest is not greater than x, return -1. Otherwise add one to taps and move covered to farthest.
  5. When the walk is over, return taps.

The main method runs the three examples, a garden that is a single point (n = 0), a garden with a dry stretch in the middle, and a garden where every tap has range 1.

Java
public class MinimumNumberOfTapsToWaterGarden {

    public static int minTaps(int n, int[] ranges) {
        int[] reachFrom = new int[n + 1];  // farthest right end of a tap starting at x
        for (int i = 0; i <= n; i++) {
            int left = Math.max(0, i - ranges[i]);
            int right = Math.min(n, i + ranges[i]);
            reachFrom[left] = Math.max(reachFrom[left], right);
        }
        int taps = 0;
        int covered = 0;   // [0, covered] is watered by the taps opened so far
        int farthest = 0;  // how far one more tap, starting inside [0, covered], can reach
        for (int x = 0; x < n; x++) {
            farthest = Math.max(farthest, reachFrom[x]);
            if (x == covered) {                // the water runs out here
                if (farthest <= x) {
                    return -1;                 // no tap waters the stretch just after x
                }
                taps++;
                covered = farthest;
            }
        }
        return taps;
    }

    public static void main(String[] args) {
        System.out.println(minTaps(5, new int[] {3, 4, 1, 1, 0, 0}));
        System.out.println(minTaps(3, new int[] {0, 0, 0, 0}));
        System.out.println(minTaps(7, new int[] {1, 2, 1, 0, 2, 1, 0, 1}));
        System.out.println(minTaps(0, new int[] {0}));
        System.out.println(minTaps(4, new int[] {1, 0, 0, 0, 1}));
        System.out.println(minTaps(6, new int[] {1, 1, 1, 1, 1, 1, 1}));
    }
}

Running it prints:

Output
1
-1
3
0
-1
3

The 3 on the third line is Example 3: taps 1, 4 and 7, the orange bars in the picture. The 0 below it comes from n = 0, where the garden is the single point 0. The walk never starts, and no tap needs opening.

The fifth line, -1, comes from [1, 0, 0, 0, 1] with n = 4. Tap 0 waters 0 to 1 and tap 4 waters 3 to 4, while taps 1, 2 and 3 wet only their own points, so the ground from 1 to 3 stays dry. In the last line, seven taps of range 1 cover a garden from 0 to 6 with three of them: taps 1, 3 and 5.

The check farthest <= x is what produces both -1 lines. Without it, the second line prints 1 and the fifth prints 2. In Example 2, one tap is counted at x = 0, but covered stays at 0, and the walk then runs out without noticing the dry ground.

Complexity

The work is one loop over the taps and one walk along the garden.

  • Time: O(n), because the first loop handles each of the n + 1 taps once, and the walk visits each point from 0 to n - 1 once with a fixed amount of work there.
  • Space: O(n), because reachFrom holds one number for each of the n + 1 points, while the walk keeps only three counters.

Video Stitching asks the same question about video clips instead of taps, and the same walk solves it.