Corporate Flight Bookings Problem
Description
LeetCode Problem 1109.
There are n flights that are labeled from 1 to n.
You are given an array of flight bookings bookings, where bookings[i] = [first_i, last_i, seats_i] represents a booking for flights first_i through last_i (inclusive) with seats_i seats reserved for each flight in the range.
Return an array answer of length n, where answer[i] is the total number of seats reserved for flight i.
Example 1:
Input: bookings = [[1,2,10],[2,3,20],[2,5,25]], n = 5
Output: [10,55,45,25,25]
Explanation:
Flight labels: 1 2 3 4 5
Booking 1 reserved: 10 10
Booking 2 reserved: 20 20
Booking 3 reserved: 25 25 25 25
Total seats: 10 55 45 25 25
Hence, answer = [10,55,45,25,25]
Example 2:
Input: bookings = [[1,2,10],[2,2,15]], n = 2
Output: [10,25]
Explanation:
Flight labels: 1 2
Booking 1 reserved: 10 10
Booking 2 reserved: 15
Total seats: 10 25
Hence, answer = [10,25]
Constraints:
1 <= n <= 2 * 10^41 <= bookings.length <= 2 * 10^4bookings[i].length == 31 <= first_i <= last_i <= n1 <= seats_i <= 10^4
Solution
Approach: Difference Array
Adding seats to every flight in first..last for each booking works, but it costs O(n) per booking, about 4 · 108 steps in the worst case.
Instead, record only where each booking starts and stops. In a difference array diff, diff[i] is how much the seat count changes from flight i - 1 to flight i. A booking changes just two of these:
- at
first, the count goes up byseats; - right after
last, it goes back down byseats.
After all bookings are recorded, a running (prefix) sum over diff turns the changes back into the actual totals: the total for flight i is the sum of all changes up to i.
Watch the indexes: flights are numbered from 1, so with a 0-based array the +seats goes at index first - 1 and the -seats at index last. When last == n, the booking runs to the end and there is no "after" to record, so that update is skipped (or use an array one longer than n).
Complexity: O(n + m) time for m bookings, and O(1) extra space besides the answer, which doubles as the difference array.
class Solution:
def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:
# ans starts as a difference array: ans[i] = seats(flight i) - seats(flight i - 1), 0-based
ans = [0] * n
for first, last, seats in bookings:
ans[first - 1] += seats
if last < n:
ans[last] -= seats # flight last + 1 (index last) no longer has them
for i in range(1, n):
ans[i] += ans[i - 1] # prefix sums turn it into the totals
return ans