Open the Minimum Number of Sprinklers to Cover a Garden
QuinceSoftware Engineer · Online AssessmentLast updated
This problem tests greedy algorithm design and interval scheduling techniques to solve a coverage optimization task.
Problem Statement
You are tasked with watering a garden represented as a line segment from 0 to L. You are given n sprinklers. Each sprinkler i is located at position p[i] and has a range r[i], meaning it covers the interval [p[i] - r[i], p[i] + r[i]].
Your goal is to select the minimum number of sprinklers needed such that the entire interval [0, L] is covered. If it is impossible to cover the garden, return -1.
Function Signature
def min_sprinklers(L, p, r) -> int:
Examples
Example 1:
L = 10,p = [1, 3, 5, 8],r = [2, 2, 2, 2]- Intervals:
[-1, 3], [1, 5], [3, 7], [6, 10] - Output:
3(e.g., using intervals[-1, 3], [3, 7], [6, 10]covers[0, 10])
Example 2:
L = 5,p = [1, 2],r = [0.5, 0.5]- Output:
-1(Gaps exist in the coverage).
Constraints
0 <= L <= 10^61 <= n <= 10^5-10^6 <= p[i] <= 10^60 <= r[i] <= 10^6
Edge Cases
- The garden is already covered with one sprinkler.
- No combination of sprinklers can bridge the gap between
0andL. - Sprinklers may have negative coverage ranges (outside the [0, L] bounds).
Hints
Hint 1
Transform each sprinkler into an interval `[start, end]` clipped to `[0, L]`.
Hint 2
Sort the intervals by their starting position to process them greedily.
Hint 3
At each step, keep track of the farthest reach achievable from the current covered boundary and jump to the next interval that starts before or at that boundary.
Follow-up questions
- What is the time complexity of your solution if you sort the intervals first?
- How would the algorithm change if each sprinkler had a different 'cost' and you wanted to minimize total cost rather than the number of sprinklers?
- What data structures would you use if the garden was a 2D plane instead of a 1D line?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.