Tutorialspoint
Problem
Solution
Submissions

Number of Taps to Water Garden

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 15

Write a C program to find the minimum number of taps needed to water a garden. There is a one-dimensional garden on the x-axis. The garden starts at x = 0 and ends at x = n. There are n + 1 taps located at points [0, 1, 2, ..., n] on the x-axis. 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.

Example 1
  • Input: n = 5, ranges = [3,4,1,1,0,0]
  • Output: 1
  • Explanation:
    The tap at point 0 can cover range [-3, 3].
    The tap at point 1 can cover range [-3, 5].
    Since tap at point 1 covers [0, 5] completely, only 1 tap is needed.
    Therefore, minimum taps needed = 1.
Example 2
  • Input: n = 3, ranges = [0,0,0,0]
  • Output: -1
  • Explanation:
    All taps have range 0, so each can only water their own point.
    Tap 0 covers [0,0], tap 1 covers [1,1], tap 2 covers [2,2], tap 3 covers [3,3].
    No tap can cover multiple points, impossible to water entire garden [0,3].
    Therefore, return -1.
Constraints
  • 1 ≤ n ≤ 10^4
  • ranges.length == n + 1
  • 0 ≤ ranges[i] ≤ 100
  • Time Complexity: O(n^2)
  • Space Complexity: O(n)
ArraysCognizantApple
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Convert the tap ranges into intervals that each tap can cover
  • Use greedy approach to select minimum taps
  • For each position, find the tap that extends the farthest
  • Keep track of current coverage and next possible coverage
  • If at any point coverage gap exists, return -1
  • Count the number of taps used during the process

Steps to solve by this approach:

 Step 1: Convert tap positions and ranges into maximum reachable positions from each point
 Step 2: Create an array to store the farthest point reachable from each position
 Step 3: Iterate through each position and update the maximum reach possible
 Step 4: Use greedy approach to select minimum taps by always choosing the tap that extends coverage the farthest
 Step 5: Keep track of current coverage end and farthest possible reach
 Step 6: If at any point we cannot extend coverage, return -1
 Step 7: Count and return the total number of taps used

Submitted Code :