Practice problem · medium
A ride-sharing van drives along a straight road marked in kilometres. Each booking has a group of passengers who are picked up at one kilometre mark and dropped off at a later one. The van holds a fixed number of passengers.
At a stop, passengers getting off leave before new passengers get on. You get the bookings and the capacity of the van. Find the first kilometre mark at which the van would be over capacity.
Write first_overload(passengers, pickup, dropoff, capacity).
i has passengers[i] people, picked up at pickup[i] and dropped off at dropoff[i], with pickup[i] < dropoff[i].pickup[i] up to, but not including, dropoff[i].capacity. Return -1 if that never happens.Input: passengers = [2, 1, 3], pickup = [1, 2, 4], dropoff = [5, 4, 8], capacity = 4
Output: 4Turn each booking into two events: people get on at the pickup mark, and get off at the drop-off mark. Sort the events by mark, with get-off events first at the same mark. Then add up.
| Mark | Event | People on board | Over 4? |
|---|---|---|---|
| 1 | 2 get on | 2 | no |
| 2 | 1 gets on | 3 | no |
| 4 | 1 gets off | 2 | no |
| 4 | 3 get on | 5 | yes: mark 4 |
The van is over capacity at mark 4.
Input: passengers = [2, 3], pickup = [1, 5], dropoff = [5, 7], capacity = 3
Output: -1At mark 5, the first group gets off before the second group gets on. The van never holds more than 3 people.
Input: passengers = [3], pickup = [1], dropoff = [5], capacity = 2
Output: 1One group of 3 is already more than the capacity of 2 when it gets on at mark 1.
0 ≤ passengers.length = pickup.length = dropoff.length ≤ 100,000 (bookings)1 ≤ passengers[i] ≤ 1000 ≤ pickup[i] < dropoff[i] ≤ 1,000,000,000 (kilometre marks)1 ≤ capacity ≤ 1,000,000Adding up the people on board at every pickup mark, by checking every booking, costs about n × n, which is 10^10 at n = 100,000. Marks go up to 10^9, so an array with one cell for each mark is too big. Sorting the 2n events costs about n log n.
first_overload · runs in your browserCoding is easiest on a laptop. On a phone, read, trace and try small edits.