Problem Description
Given a one-dimensional garden represented by the interval [0, n] and n+1 water taps placed at positions 0 through n, each tap i can water an interval defined by [i - ranges[i], i + ranges[i]]. The goal is to determine the minimum number of taps needed such that their watered intervals cover the whole garden. If it is impossible to water the entire garden, return -1.
Key Insights
- The problem can be transformed into an interval covering problem.
- Each tap defines an interval. Preprocess taps to calculate the farthest right point each interval can cover.
- A greedy approach can be used similar to the "jump game" strategy, trying to extend coverage as far as possible.
- Checking if the current interval cannot be extended further is crucial to determine if the garden cannot be fully watered.
Space and Time Complexity
Time Complexity: O(n) – Preprocessing the intervals takes O(n) and the greedy traversal is O(n). Space Complexity: O(n) – An additional array is used to store the maximum reach for each starting point.
Solution
The solution begins by converting each tap’s position and range into an interval. Instead of considering individual intervals directly, we create an array (maxRange) where for any index i, maxRange[i] stores the farthest point we can reach from any tap that starts its interval at i. Using this preprocessed information, a greedy algorithm scans the garden from left to right. At every point i within the current reachable region, we update the next farthest reach. Once we reach the end of the current region, we select that as our new coverage endpoint and increment our tap count. If at any point the next coverage region does not extend beyond the current, the garden cannot be fully watered and the answer is -1.