Minimum Number of Taps to Open to Water a Garden - Problem
There is a one-dimensional garden on the x-axis. The garden starts at point 0 and ends at point n (i.e., the length of the garden is n).
There are n + 1 taps located at points [0, 1, 2, ..., n] in the garden.
Given an integer n and an integer array ranges of length n + 1 where ranges[i] (0-indexed) means the i-th tap can water the area [i - ranges[i], i + ranges[i]] if it was open.
Return the minimum number of taps that should be open to water the whole garden. If the garden cannot be watered, return -1.
Input & Output
Example 1 — Basic Case
$
Input:
n = 5, ranges = [3,4,1,1,0,0]
›
Output:
1
💡 Note:
Tap at index 1 has range 4, so it can water area [1-4, 1+4] = [-3,5]. Since we only need [0,5], tap 1 alone covers the entire garden.
Example 2 — Multiple Taps Needed
$
Input:
n = 3, ranges = [0,0,0,0]
›
Output:
-1
💡 Note:
No tap has any range (all ranges are 0), so no tap can water any area beyond its own position. Cannot water the entire garden.
Example 3 — Optimal Selection
$
Input:
n = 7, ranges = [1,2,1,0,2,1,0,1]
›
Output:
3
💡 Note:
We can use taps at positions 1, 4, and 7. Tap 1 covers [0,3], tap 4 covers [2,6], tap 7 covers [6,8]. Together they cover [0,7].
Constraints
- 1 ≤ n ≤ 104
- ranges.length == n + 1
- 0 ≤ ranges[i] ≤ 100
Visualization
Tap to expand
Understanding the Visualization
1
Input
Garden of length n=5, taps at positions 0-5 with given ranges
2
Coverage
Each tap covers interval [position - range, position + range]
3
Output
Minimum number of taps needed to cover entire garden [0,n]
Key Takeaway
🎯 Key Insight: Use greedy approach - at each step pick the tap that extends coverage furthest, similar to Jump Game II
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code