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
Minimum Taps to Water Garden INPUT Garden: 0 to n=5 0 5 ranges = [3,4,1,1,0,0] Tap Coverage Areas: Tap0: [-3,3] Tap1: [-3,5] FULL! Tap2: [1,3] Tap3: [2,4] Tap4: [4,4] Tap5: [5,5] n = 5 ranges = [3,4,1,1,0,0] ALGORITHM STEPS (Greedy Approach) 1 Convert to Intervals Each tap creates [i-r, i+r] maxReach[start] = max end 2 Initialize Variables taps=0, currEnd=0, farthest=0 Start from position 0 3 Greedy Selection For each pos, track max reach farthest = max(farthest, reach) 4 Check Coverage When pos==currEnd, extend currEnd=farthest, taps++ Execution: Tap1 covers [-3, 5] 5 >= n (garden length) One tap is enough! taps = 1 FINAL RESULT Optimal Solution Visualization Garden 0 to 5 0 1 2 3 4 5 Selected Tap: Tap 1 Position: 1 Range: 4 Coverage: [-3, 5] Covers entire garden! Output: 1 Minimum taps needed: 1 OK - Garden fully watered Key Insight: The greedy approach transforms tap ranges into intervals and selects taps that extend coverage the farthest. At each position, we track the maximum reachable point. When current coverage ends, we extend to the farthest reachable point and increment tap count. Time: O(n), Space: O(n). TutorialsPoint - Minimum Number of Taps to Open to Water a Garden | Greedy Approach
Asked in
Google 23 Amazon 18 Microsoft 12 Apple 8
52.0K Views
Medium Frequency
~25 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen