Ride-hailing app~20 min2s · 256 MBtarget O(n + q) time, O(n) spaceclassic twin: lc-1109difference-array
A travel app sells group bookings on a daily shuttle service. A booking reserves the same number of seats on every flight from one flight number to another, both included.
The airline wants to know how many seats are booked on every flight, to decide where to add capacity. Flights are numbered from 1. A service can have 100,000 flights, and the app can hold 100,000 bookings.
Write seats_per_flight(flights, bookings).
flights flights, numbered 1 to flights.bookings[j] is [first, last, seats] with 1 <= first <= last <= flights. It reserves seats seats on every flight from first to last, both included.flights numbers: the seats booked on flight 1, flight 2, and so on. Totals can pass 2,000,000,000, so use 64-bit integers.Input: flights = 5, bookings = [[1, 3, 10], [2, 5, 20], [2, 2, 25], [4, 5, 15]]
Output: [10, 55, 30, 35, 35]Each booking writes two notes. The change list uses places 0 to 5, one for each flight number minus 1, plus one extra.
| Booking | Notes written | Change list after |
|---|---|---|
| [1, 3, 10] | +10 at 0, -10 at 3 | [10, 0, 0, -10, 0, 0] |
| [2, 5, 20] | +20 at 1, -20 at 5 | [10, 20, 0, -10, 0, -20] |
| [2, 2, 25] | +25 at 1, -25 at 2 | [10, 45, -25, -10, 0, -20] |
| [4, 5, 15] | +15 at 3, -15 at 5 | [10, 45, -25, 5, 0, -35] |
The running totals of the first 5 places are 10, 55, 30, 35 and 35.
Input: flights = 1, bookings = [[1, 1, 7]]
Output: [7]One flight, one booking.
Input: flights = 3, bookings = [[2, 3, 5]]
Output: [0, 5, 5]A booking that reaches the last flight.
1 ≤ flights ≤ 100,0001 ≤ bookings.length ≤ 100,0001 ≤ first ≤ last ≤ flights and 1 ≤ seats ≤ 100,000A booking can cover every flight. With 100,000 flights and 100,000 bookings, adding the seats flight by flight costs up to 10^10 additions.
Two writes for each booking and one pass cost about 3 × 10^5 steps. Totals can reach 10^10, so use 64-bit integers.