Shared Telescope Night

MediumintervalsAlso known as Non-overlapping Intervals

A university observatory has one big telescope, and astronomers send in requests for time on it. Each request is a window of minutes measured from midnight: [-90, -30] means 10:30 pm to 11:30 pm, and [30, 90] means 12:30 am to 1:30 am.

Only one astronomer can use the telescope at a time, though one session may start the very minute another ends. Too many requests came in for tonight. The scheduler wants to turn down as few of them as possible.

Your task

Write fewestToDecline(requests). Each request is [start, end] with start < end. Return the smallest number of requests to remove so that no two remaining requests overlap.

Two requests overlap if one starts before the other ends. Requests that only touch, like [0, 60] and [60, 120], do not overlap. An empty list returns 0.

fewestToDecline(requests: int[][]) → int

Examples

Example 1
Input
requests = [[0, 180], [30, 60], [60, 120], [150, 240]]
Output
1
Why

Turn down [0, 180]. The other three then fit one after another: 30 to 60, 60 to 120, and 150 to 240. Declining fewer is impossible, because [0, 180] overlaps all three others, and you cannot keep it alongside them.

Example 2
Input
requests = [[-60, 30], [-90, -30], [30, 90]]
Output
1
Why

[-90, -30] and [-60, 30] overlap between -60 and -30, so one of them must go. Decline either one: [30, 90] fits after both, since a session may start the minute another ends. So only 1 request is turned down.

Constraints

  • 0 ≤ requests.length ≤ 10,000
  • -1,000,000,000 ≤ start < end ≤ 1,000,000,000
Start with brute force

Try every subset of requests, check whether it has no overlaps, and keep the largest valid one. The answer is the total minus that size.

There are 2n subsets. With 40 requests that is already about a trillion, and the limit here is 10,000. You need a rule that picks the right requests without trying combinations.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code