1381. Limited Overlap Calendar

Medium3.5 points estimatedOrdered SetDesignLine SweepIntervals

A lecture hall can host at most k events at the same moment. Design the class LimitedOverlapCalendar whose constructor takes the integer k, with one method book(start, end) for the half-open event [start, end).

If, after adding the event, no instant is covered by more than k accepted events, the event is accepted and book returns -1. Otherwise the event is rejected, the calendar stays exactly as it was, and book returns the smallest instant t in [start, end) that would have been covered by more than k events. An event that ends exactly when another begins does not overlap it.

Keep an ordered map of boundaries (+1 at each start, -1 at each end) and sweep it in key order on every call, tentatively including the new event. With n accepted events one call costs O(n log n); n is at most 1000.

Example 1

Input:
operations = ["LimitedOverlapCalendar","book","book","book","book","book"]arguments = [[1],[10,20],[15,25],[20,30],[5,10],[0,40]]
Output:
[null,-1,15,-1,-1,5]
Explanation:

With k = 1 the first event is accepted, [15,25) would put time 15 under two events so it returns 15, [20,30) only touches it and is accepted, [5,10) is accepted, and [0,40) first collides at 5.

Example 2

Input:
operations = ["LimitedOverlapCalendar","book","book","book","book"]arguments = [[2],[1,5],[2,6],[3,7],[4,8]]
Output:
[null,-1,-1,3,4]
Explanation:

Two events may overlap; the third would give three at time 3 and is rejected with 3, and the fourth reaches three at time 4 and is rejected with 4.

Example 3

Input:
operations = ["LimitedOverlapCalendar","book"]arguments = [[3],[7,8]]
Output:
[null,-1]
Explanation:

A single event on an empty calendar is accepted.

Constraints

1 ≤ k ≤ 10

1 ≤ number of book calls ≤ 1000

0 ≤ start < end ≤ 109

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Input
Each case is an operation log. operations names the class first and then each method call; arguments holds the arguments for each, in the same order. Your answer is one list with a result per operation - null for the constructor and for methods that return nothing.

Expected complexity

Time
O(n log n) per call
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…

operations names the class, then each method to call; arguments holds one list of arguments per operation, in the same order.