Shared Telescope Night

MediumintervalsAlso known as Non-overlapping Intervals

Astronomers request time on an observatory's one big telescope. Each request is a window of minutes from midnight: [-90, -30] is 10:30 pm to 11:30 pm, and [30, 90] is 12:30 am to 1:30 am.

Only one astronomer can use it at a time, though a session may start the minute another ends. Too many requests came in tonight, and the scheduler wants to turn down as few 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

Declining [0, 180] is enough, because the other three then fit one after another: 30 to 60, 60 to 120, and 150 to 240. Declining nothing is impossible because [0, 180] overlaps all three of the others.

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 be declined. Either choice works, because [30, 90] fits after both, since a session may start the minute another ends. The answer is 1.

Constraints

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

Try every subset, check it has no overlaps, and keep the largest. The answer is the total minus its size.

There are 2n subsets: about a trillion for 40 requests, and the limit here is 10,000. You need a rule that picks 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