1391. Overload Removals

Hard7.5 points estimatedLine SweepGreedyHeapIntervals

A hall hosts workshops, and workshop i occupies the half-open time interval from starts[i] up to but not including starts[i] + lengths[i]. The fire code allows at most k workshops to be running at any single instant, and a workshop that ends at the moment another begins does not overlap it.

Cancel as few workshops as possible so that, among the ones that remain, no instant is covered by more than k of them. Return the number of cancelled workshops. Only the count is returned, so which ones are cancelled does not matter. Start times and lengths can reach 10^9, so end times can pass the 32-bit range. With 10^5 workshops aim for O(n log n) time and O(n) space.

Example 1

Input:
starts = [1,2,3], lengths = [5,5,5], k = 2
Output:
1
Explanation:

At time 3 all three intervals are active, so one must go, and removing any one fixes it.

Example 2

Input:
starts = [1,2,3], lengths = [5,5,5], k = 3
Output:
0
Explanation:

At most three intervals ever overlap, which the limit allows, so nothing is removed.

Example 3

Input:
starts = [1,1,1,1], lengths = [4,3,2,1], k = 2
Output:
2
Explanation:

All four start together, so two must be removed, and dropping the two that end latest suffices.

Constraints

1 ≤ n ≤ 105; starts.length == lengths.length == n; 1 ≤ k ≤ n; 0 ≤ starts[i] ≤ 109; 1 ≤ lengths[i] ≤ 109.

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 2,400 msC++ 600 msJava 1,200 msJavaScript 1,200 msTypeScript 1,200 ms

Expected complexity

Time
O(n log n)
Space
O(n)

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…