Minimum Number of Taps to Open to Water a Garden
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^4ranges.length == n + 10 <= 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.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
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.
| Approach | Time | Space |
|---|---|---|
| Brute force (DP over positions) | O(n²) | O(n) |
| Optimal (greedy jumps) | O(n) | O(n) |
1Brute force (DP over positions)
O(n²)n positions times n + 1 taps.O(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.
dp[0] = 0; every other entry starts as infinity.- For
j = 1..n, for each tapiwithl = max(0, i - r),rr = min(n, i + r): ifl < j <= rr, setdp[j] = min(dp[j], dp[l] + 1). - 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];
}
}class Solution:
def minTaps(self, n: int, ranges: List[int]) -> int:
INF = float("inf")
dp = [INF] * (n + 1)
dp[0] = 0
for j in range(1, n + 1):
for i in range(n + 1):
l = max(0, i - ranges[i])
r = min(n, i + ranges[i])
if l < j <= r:
dp[j] = min(dp[j], dp[l] + 1)
return -1 if dp[n] == INF else dp[n]class Solution {
public:
int minTaps(int n, vector<int>& ranges) {
const int INF = INT_MAX / 2;
vector<int> dp(n + 1, INF);
dp[0] = 0;
for (int j = 1; j <= n; j++) {
for (int i = 0; i <= n; i++) {
int l = max(0, i - ranges[i]);
int r = min(n, i + ranges[i]);
if (l < j && j <= r) dp[j] = min(dp[j], dp[l] + 1);
}
}
return dp[n] >= INF ? -1 : dp[n];
}
};function minTaps(n, ranges) {
const dp = new Array(n + 1).fill(Infinity);
dp[0] = 0;
for (let j = 1; j <= n; j++) {
for (let i = 0; i <= n; i++) {
const l = Math.max(0, i - ranges[i]);
const r = Math.min(n, i + ranges[i]);
if (l < j && j <= r) dp[j] = Math.min(dp[j], dp[l] + 1);
}
}
return dp[n] === Infinity ? -1 : dp[n];
}2Optimal (greedy jumps)
O(n)One pass to build `far`, one pass to sweep.O(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.
far[max(0, i - r)] = max(far[...], min(n, i + r))for every tap.taps = 0, end = 0, best = 0. Fori = 0..n-1:best = max(best, far[i]).- If
i == end: ifbest <= ireturn -1; otherwisetaps++andend = best. - 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;
}
}class Solution:
def minTaps(self, n: int, ranges: List[int]) -> int:
far = [0] * (n + 1)
for i in range(n + 1):
l = max(0, i - ranges[i])
far[l] = max(far[l], min(n, i + ranges[i]))
taps = end = best = 0
for i in range(n):
best = max(best, far[i])
if i == end:
if best <= i:
return -1
taps += 1
end = best
return tapsclass Solution {
public:
int minTaps(int n, vector<int>& ranges) {
vector<int> far(n + 1, 0);
for (int i = 0; i <= n; i++) {
int l = max(0, i - ranges[i]);
far[l] = max(far[l], min(n, i + ranges[i]));
}
int taps = 0, end = 0, best = 0;
for (int i = 0; i < n; i++) {
best = max(best, far[i]);
if (i == end) {
if (best <= i) return -1;
taps++;
end = best;
}
}
return taps;
}
};function minTaps(n, ranges) {
const far = new Array(n + 1).fill(0);
for (let i = 0; i <= n; i++) {
const l = Math.max(0, i - ranges[i]);
far[l] = Math.max(far[l], Math.min(n, i + ranges[i]));
}
let taps = 0, end = 0, best = 0;
for (let 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.