Ride-hailing app~40 min2s · 256 MBtarget O((b + m) log b) time, O(b) spaceclassic twin: lc-2402heaps · intervals
A ride-hailing app runs a depot with charging bays for its fleet. Cars ask for a stay, with a start time and an end time. The depot handles the requests in order of start time.
Your team lead asks: "A request takes the lowest free bay. If all bays are busy, it waits for the first one to free and keeps its length. Which bay is used by the most cars?"
Write busiest_bay(bays, starts, ends).
0 to bays - 1. Request i asks for a stay that starts at starts[i] and ends at ends[i], so its length is ends[i] - starts[i]. All start times are different, and the requests are not sorted.t if its current stay ends at t or earlier. A request takes the free bay with the smallest number, and starts at its own start time.Input: bays = 2, starts = [3, 0, 1, 2, 9], ends = [7, 10, 5, 4, 12]
Output: 1The table lists the requests in start order, with the bays that are free at that time, the bay used, and the time the bay is busy until.
| Request | Start | Free bays | Bay used | Busy until | Note |
|---|---|---|---|---|---|
| 1 | 0 | 0, 1 | 0 | 10 | |
| 2 | 1 | 1 | 1 | 5 | |
| 3 | 2 | none | 1 | 7 | waits until 5, length 2 |
| 0 | 3 | none | 1 | 11 | waits until 7, length 4 |
| 4 | 9 | none | 0 | 13 | waits until 10, length 3 |
Bay 0 took 2 requests and bay 1 took 3, so the answer is 1.
Input: bays = 1, starts = [5, 0], ends = [8, 4]
Output: 0There is only one bay, so it takes both requests.
Input: bays = 3, starts = [0, 5, 10], ends = [2, 7, 12]
Output: 0The stays never overlap, so bay 0 is free each time and takes all three.
1 ≤ bays ≤ 100,0001 ≤ length of starts ≤ 100,000, and ends has the same length.0 ≤ starts[i] < ends[i] ≤ 10^9, and all the start times are different.With 50,000 bays and 100,000 long requests, looking at every bay for each request is up to 100,000 × 50,000 = 5,000,000,000 checks. The time limit allows a few hundred million.
Two heaps need about 3 heap steps for each request, at about 17 comparisons each. That is about 5 million steps.