sagelearnai

Corporate Flight Bookings

Difficulty: Medium · Pattern: Prefix Sum · LeetCode #1109

There are n flights numbered 1…n. Each booking [first, last, seats] reserves seats on every flight from first to last inclusive. Return an array with the total seats reserved per flight.

Examples

text
bookings = [[1,2,10],[2,3,20],[2,5,25]], n = 5  →  [10, 55, 45, 25, 25]
bookings = [[1,2,10],[2,2,15]], n = 2           →  [10, 25]

Hints

  1. Updating every flight in each range is O(n) per booking.
  2. A difference array records only where each range starts and ends.

Approach

Create diff of size n+1. For each booking, diff[first−1] += seats and diff[last] −= seats. The prefix sum of diff gives each flight's total. Each range update becomes O(1), and one final O(n) pass reconstructs the totals. This is the inverse of prefix sums.

Complexity

Time: O(n + bookings). Space: O(n).

Python solution
def corpFlightBookings(bookings, n):
    diff = [0] * (n + 1)
    for first, last, seats in bookings:
        diff[first - 1] += seats
        diff[last] -= seats
    out, s = [], 0
    for i in range(n):
        s += diff[i]
        out.append(s)
    return out
JavaScript solution
function corpFlightBookings(bookings, n) {
  const diff = new Array(n + 1).fill(0);
  for (const [f, l, s] of bookings) { diff[f - 1] += s; diff[l] -= s; }
  const out = []; let s = 0;
  for (let i = 0; i < n; i++) { s += diff[i]; out.push(s); }
  return out;
}