Fewest intervals to remove
Each item of intervals is a pair [start, end] with start < end. Think of it as a booking of one room from start until end. Two bookings clash when each one starts before the other ends. A booking that ends at 4 and one that starts at 4 do not clash: the first is over when the second begins. The bookings come in any order.
Remove as few bookings as you can so that no two of the bookings left clash, and return how many you removed.
This endpoint rule is the opposite of merge intervals, where touching intervals merged. Check the rule in every interval problem.
intervals = [[1, 3], [2, 4], [3, 5]]Output1Remove [2, 4]. Then [1, 3] and [3, 5] only touch at 3, which is allowed.
intervals = [[1, 10], [2, 3], [4, 5], [6, 7]]Output1Remove the long [1, 10]. The three short bookings fit one after another.
intervals = [[3, 6], [3, 6], [3, 6]]Output2Equal bookings all clash with each other, so only one can stay.
0 ≤ len(intervals) ≤ 105
-5 × 104 ≤ start < end ≤ 5 × 104
Plan it first
Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.