1379. Overlap Registry

Medium3.5 points estimatedOrdered SetDesignIntervalsBinary Search

A studio keeps a registry of recorded sessions, each one a half-open time range [start, end). Design the class OverlapRegistry with an empty constructor and two methods.

add(start, end) stores the range and returns nothing. The same range may be added several times, and every copy counts separately.

countOverlapping(start, end) returns how many stored ranges share a positive length with the query range [start, end). Ranges that merely touch at one point do not overlap. Hint: a stored range is disjoint from the query exactly when it ends at or before start or begins at or after end, and no range can be both, so the answer is the total count minus those two counts. Keep the starts and the ends in two sorted lists and binary search them.

Queries must take O(log n) time to search; n never exceeds 2000.

Example 1

Input:
operations = ["OverlapRegistry","add","add","countOverlapping","countOverlapping","add","countOverlapping"]arguments = [[],[1,5],[4,8],[5,7],[0,1],[1,5],[2,3]]
Output:
[null,null,null,1,0,null,2]
Explanation:

The query [5,7) overlaps only [4,8); [0,1) only touches [1,5) so it counts 0; after the duplicate [1,5) is added, [2,3) overlaps both copies.

Example 2

Input:
operations = ["OverlapRegistry","countOverlapping"]arguments = [[],[0,10]]
Output:
[null,0]
Explanation:

Nothing has been added yet, so the count is 0.

Example 3

Input:
operations = ["OverlapRegistry","add","countOverlapping","countOverlapping"]arguments = [[],[0,1000000000],[999999999,1000000000],[0,1]]
Output:
[null,null,1,1]
Explanation:

The single huge range overlaps every query inside it.

Constraints

1 ≤ number of calls ≤ 2000

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(log n) per query, O(n) per insert
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.