Problem 331610 · medium · Phase 03 Linear Management & Searching

Fewest Sprinklers to Wet the Path

greedy · intervals · covering

A garden path is the closed segment [0, L]. Each sprinkler wets a closed range [a, b]. Choose the fewest sprinklers whose ranges together wet every point of the path, and return that number. Ranges may extend beyond the path, and two ranges that touch ([0, 3] and [3, 6]) leave no dry point between them. Return -1 if the path cannot be fully wetted.

Examples

Input:  L = 10, ranges = [[0, 3], [2, 6], [3, 5], [6, 10], [7, 9]]
Output: 3
Explanation: [0, 3], [2, 6] and [6, 10].
Input:  L = 5, ranges = [[0, 2], [3, 5]]
Output: -1
Explanation: The stretch between 2 and 3 stays dry.

Constraints

  • 1 <= L <= 10**9, 0 <= len(ranges) <= 5 * 10**4, 0 <= a <= b <= 10**9.
  • Target complexity: O(n log n).

Goals

  • Extend coverage one greedy jump at a time to the farthest reachable point
  • Detect an uncoverable gap and report it
Starting Python…