1491. First Overbooked Request

Medium3.5 points estimatedBinary SearchPrefix SumArray

A campsite has n days on its calendar, numbered from 0, and on day d it can host at most capacity[d] guests. Booking requests arrive one after another in the order given. Request j is requests[j] = [l, r, seats], meaning that seats extra guests stay on every day from l to r, both included. All requests are accepted without checking; the owner just wants to know when trouble starts.

Return the 0-based index of the earliest request after which some day has more guests than its capacity. If no day is ever over capacity, return -1. Because seat counts are positive, once a day is overbooked it stays overbooked, so the earliest such request is unique. Aim for O((n + q) log q) time with a difference array per probe, where q is the number of requests, and O(n) extra space.

Example 1

Input:
capacity = [3,3,3], requests = [[0,1,2],[1,2,2],[0,2,1]]
Output:
1
Explanation:

After the second request day 1 holds 4 guests, above its capacity of 3, so index 1 is the first to overbook.

Example 2

Input:
capacity = [5,5], requests = [[0,1,3],[1,1,2]]
Output:
-1
Explanation:

Day 1 reaches exactly 5, which equals its capacity but never exceeds it, so the answer is -1.

Example 3

Input:
capacity = [0], requests = [[0,0,1]]
Output:
0
Explanation:

A capacity of 0 is exceeded by the very first request, so the answer is 0.

Constraints

1 ≤ n ≤ 1000

1 ≤ requests.length ≤ 1000

0 ≤ l ≤ r < n

1 ≤ seats ≤ 104

0 ≤ capacity[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 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O((n + q) log q)
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…