Engineering platform~15 min2s · 256 MBtarget O(n log n) time, O(n) spaceclassic twin: lc-435greedy · sorting
You work on the booking tool behind an engineering platform. One meeting room receives a list of requests, each with a start time and an end time, in minutes from the start of the day.
Two meetings clash when they overlap. A meeting that starts at the minute another one ends does not clash. Your team lead asks: "Which requests do we cancel so that no two clash, and how few is that?"
Write fewest_to_remove(meetings).
meetings[i] is a pair [start, end] with start < end.Input: meetings = [[1, 4], [2, 3], [3, 5], [4, 6]]
Output: 2Sort by end time: [2, 3], [1, 4], [3, 5], [4, 6]. Keep a meeting when it starts at or after the end of the last one kept.
| Meeting | Last end kept | Starts at or after it? | Kept so far |
|---|---|---|---|
[2, 3] |
none | yes | 1 |
[1, 4] |
3 | no (1 < 3) | 1 |
[3, 5] |
3 | yes (3 ≥ 3) | 2 |
[4, 6] |
5 | no (4 < 5) | 2 |
Two meetings are kept out of four, so two are removed.
Input: meetings = [[1, 2], [2, 3]]
Output: 0The second meeting starts when the first ends. They do not clash, so nothing is removed.
Input: meetings = [[1, 3], [1, 3], [1, 3]]
Output: 2All three clash with each other. Keep one and remove two.
0 ≤ len(meetings) ≤ 100,0000 ≤ start < end ≤ 1,000,000,000There can be 100,000 meetings. Trying every subset to keep is 2^100000 choices, and even comparing every pair of meetings is 5 billion checks. A sort costs about 1.7 million steps and one pass over the sorted list costs 100,000 more. That fits easily.