Minimum Number of Taps to Open to Water a Garden

Hard Arrays & Hashing Greedy Original on LeetCode

Minimum Number of Taps to Open to Water a Garden is a hard arrays & hashing problem solved with the greedy pattern. The best approach, optimal (greedy jumps), runs in O(n) time and O(n) space. Below are 2 approaches in Java, Python, C++ and JavaScript, from brute force (dp over positions) up.

Problem

A straight garden runs along the x-axis from point 0 to point n. There is a tap at every integer point 0, 1, ..., n, so n + 1 taps in total.

You are given an integer array ranges of length n + 1. If tap i is opened, it waters the stretch [i - ranges[i], i + ranges[i]]. Return the minimum number of taps to open so that every point of [0, n] is watered, or -1 if the garden cannot be fully watered.

Examples

Example 1

Input
n = 6, ranges = [1, 0, 3, 0, 0, 2, 0]
Output
2
Why
The tap at 2 waters [0, 5] and the tap at 5 waters [3, 7] clipped to [3, 6]; together they cover [0, 6].

Example 2

Input
n = 4, ranges = [1, 1, 0, 0, 1]
Output
-1
Why
Nothing waters the stretch between 2 and 3, so the garden can never be fully covered.

Example 3

Input
n = 5, ranges = [0, 0, 0, 5, 0, 0]
Output
1
Why
The tap at position 3 alone reaches from -2 to 8, which covers the whole garden.

Constraints

  • 1 <= n <= 10^4
  • ranges.length == n + 1
  • 0 <= ranges[i] <= 100

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 15 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Brute force (DP over positions)O(n²)O(n)
Optimal (greedy jumps)O(n)O(n)

1Brute force (DP over positions)

TimeO(n²)n positions times n + 1 taps.
SpaceO(n)The dp array of size n + 1.

Let dp[j] be the fewest taps needed to water [0, j]. A tap with interval [l, r] and l < j <= r can finish the job from dp[l]. Fill dp from left to right, trying every tap for every position.

  1. dp[0] = 0; every other entry starts as infinity.
  2. For j = 1..n, for each tap i with l = max(0, i - r), rr = min(n, i + r): if l < j <= rr, set dp[j] = min(dp[j], dp[l] + 1).
  3. Return dp[n], or -1 if it is still infinity.
class Solution {
    public int minTaps(int n, int[] ranges) {
        final int INF = Integer.MAX_VALUE / 2;
        int[] dp = new int[n + 1];
        Arrays.fill(dp, INF);
        dp[0] = 0;
        for (int j = 1; j <= n; j++) {
            for (int i = 0; i <= n; i++) {
                int l = Math.max(0, i - ranges[i]);
                int r = Math.min(n, i + ranges[i]);
                if (l < j && j <= r) dp[j] = Math.min(dp[j], dp[l] + 1);
            }
        }
        return dp[n] >= INF ? -1 : dp[n];
    }
}

2Optimal (greedy jumps)

TimeO(n)One pass to build `far`, one pass to sweep.
SpaceO(n)The `far` array of size n + 1.

Record, for every left end l, the farthest point any tap starting at l reaches. Then sweep like the minimum-jumps game: while scanning inside the current covered stretch, track the farthest reach available; when you hit the end of the stretch, open one more tap to extend to that farthest reach. If it cannot move past the current point, there is a dry gap.

  1. far[max(0, i - r)] = max(far[...], min(n, i + r)) for every tap.
  2. taps = 0, end = 0, best = 0. For i = 0..n-1: best = max(best, far[i]).
  3. If i == end: if best <= i return -1; otherwise taps++ and end = best.
  4. Return taps.
class Solution {
    public int minTaps(int n, int[] ranges) {
        int[] far = new int[n + 1];
        for (int i = 0; i <= n; i++) {
            int l = Math.max(0, i - ranges[i]);
            far[l] = Math.max(far[l], Math.min(n, i + ranges[i]));
        }
        int taps = 0, end = 0, best = 0;
        for (int i = 0; i < n; i++) {
            best = Math.max(best, far[i]);
            if (i == end) {
                if (best <= i) return -1;
                taps++;
                end = best;
            }
        }
        return taps;
    }
}

Edge cases to test

  • Every range is 0: no tap waters any stretch, answer -1
  • A single tap whose range covers everything
  • A gap of length 1 in the middle (two intervals that only touch would still be fine)
  • Taps that reach past either end of the garden must be clipped, not rejected

Hints

Hint 1

Turn each tap into an interval [max(0, i - r), min(n, i + r)]. You need the fewest intervals whose union is [0, n].

Hint 2

Intervals only need to touch: [0, 2] and [2, 5] together cover [0, 5].

Hint 3

For each left end keep only the farthest right end. Then it is exactly the minimum-jumps game: from your current reach, pick the interval that extends coverage the furthest.

FAQ

What is the best time complexity for Minimum Number of Taps to Open to Water a Garden?

Optimal (greedy jumps) runs in O(n) time and O(n) extra space. One pass to build `far`, one pass to sweep.

Which pattern does Minimum Number of Taps to Open to Water a Garden use?

It is a arrays & hashing problem that uses the greedy pattern. Other problems with the same pattern: Integer to Roman, Jump Game II, Jump Game.

Is there a brute force solution for Minimum Number of Taps to Open to Water a Garden?

Yes. Brute force (DP over positions) takes O(n²) time and O(n) space. Let dp[j] be the fewest taps needed to water [0, j].

Which edge cases should I test for Minimum Number of Taps to Open to Water a Garden?

Every range is 0: no tap waters any stretch, answer -1; A single tap whose range covers everything; A gap of length 1 in the middle (two intervals that only touch would still be fine); Taps that reach past either end of the garden must be clipped, not rejected.