KatInterview

Fewest Irrigation Devices to Water a Linear Garden

Greedy & IntervalsAuto-graded · 20 test cases
MediumAuto-gradedGreedy & Intervalsgreedyintervalssorting

Last updated

Tests greedy interval selection and the ability to handle coverage gaps in a linear range.

You need to irrigate a garden that stretches along a straight line from coordinate 0 to coordinate L. You have access to n irrigation devices. Device i is positioned at coordinate p[i] and waters everything within distance r[i] of its location, covering the segment [p[i] - r[i], p[i] + r[i]].

Determine the smallest number of devices you must activate so that every point in the segment [0, L] receives water. If complete coverage is impossible, return -1.

Write a function that takes the garden length L, a list of device positions p, and a list of device ranges r, then returns the minimum count of devices needed.

Constraints

  • 0 ≤ L ≤ 10⁶
  • 1 ≤ n ≤ 10⁵
  • -10⁶ ≤ p[i] ≤ 10⁶
  • 0 ≤ r[i] ≤ 10⁶
  • Positions and ranges may be floating-point numbers
  • Intervals are closed: a device ending at coordinate x and another starting at x connect without a gap

Examples

Example 1

Input: min_irrigation_devices(10, [1, 3, 5, 8], [2, 2, 2, 2])

Output: 3

Example 2

Input: min_irrigation_devices(5, [1, 2], [0.5, 0.5])

Output: -1

Hints

Hint 1

Convert each device into an interval and clip it to the garden boundaries [0, L]. Coverage outside the target range doesn't help.

Hint 2

Sort intervals by their starting coordinate, then use a greedy sweep: at each step, among all intervals that touch or overlap your current coverage, pick the one extending farthest to the right.

Hint 3

If at any point no interval can extend your covered region forward, a gap exists and the garden cannot be fully watered.