1418. Fewest Intervals Covering Points

Medium3.5 points estimatedIntervalsGreedySorting

A city must place sensors to monitor a list of checkpoints on a road. The array points holds the checkpoint positions (duplicates allowed). Each element intervals[k] = [l, r] is a stretch of road one sensor can watch, including both ends.

Return the fewest sensors, chosen from the given stretches, so that every checkpoint lies inside at least one chosen stretch. Return -1 if some checkpoint lies in none of the stretches. Each stretch may be chosen at most once, and choosing extra stretches never helps.

Sort both lists. For the leftmost uncovered checkpoint, among stretches with l at most that checkpoint, pick the one reaching farthest right, then skip every checkpoint it covers. Target O((p + m) log (p + m)) time, with p checkpoints and m stretches, and O(1) extra space beyond sorting.

Example 1

Input:
points = [1,5,9]intervals = [[0,6],[4,10],[8,9],[20,30]]
Output:
2
Explanation:

Stretch [0,6] covers 1 and 5, and [4,10] covers 9, so 2 sensors suffice.

Example 2

Input:
points = [3,3,3], intervals = [[3,3],[1,2]]
Output:
1
Explanation:

All three checkpoints are at 3 and the single stretch [3,3] covers them.

Example 3

Input:
points = [7], intervals = [[1,5],[8,9]]
Output:
-1
Explanation:

No stretch contains position 7, so the answer is -1.

Constraints

  • 1 ≤ points.length, intervals.length ≤ 1000
  • -109 ≤ points[i], l, r ≤ 109
  • l ≤ r for every interval

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O((p + m) log (p + m))
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…