Skip to content
DSA Patterns
Menu
Language
Difference ArrayLC #11093 of 6← PreviousNext →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Corporate Flight Bookings

Problem (restated)

n flights numbered 1..n. Bookings [first, last, seats] reserve seats on inclusive range. Return seats for each flight.

Intuition

Classic difference array: +seats at first-1, -seats at last, then prefix sum.

Approaches

Difference array

Unverified
Time O(n + m)Space O(n)

Idea. diff[l-1]+=s; if r is less than n: diff[r]-=s; prefix rebuild.

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

Trade-offs. Segment tree overkill for offline range adds.

Solution
export function corpFlightBookings(bookings: number[][], n: number): number[] {
  const diff = new Array(n).fill(0);
  for (const [f, l, s] of bookings) {
    diff[f! - 1]! += s!;
    if (l! < n) diff[l!]! -= s!;
  }
  for (let i = 1; i < n; i++) diff[i]! += diff[i - 1]!;
  return diff;
}
export function corpFlightBookings(bookings: number[][], n: number): number[] {
  const diff = new Array(n).fill(0);
  for (const [f, l, s] of bookings) {
    diff[f! - 1]! += s!;
    if (l! < n) diff[l!]! -= s!;
  }
  for (let i = 1; i < n; i++) diff[i]! += diff[i - 1]!;
  return diff;
}

Template connection

Bookings are 1-indexed range adds: diff[first - 1] += seats, and diff[last] -= seats when last < n. One prefix turns those deltas into seats per flight.

Reflection

  • last is inclusive. Why subtract at diff[last + 1], not at last?
  • Flights are numbered from 1. Slicing the answer down to 1..n catches which off-by-one?
  • No bookings: n zeros. Overlapping seats have to add up in the prefix.
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

n=5 flights. Bookings add seats on inclusive [first, last].

0
0
0
1
0
2
0
3
0
4

1-indexed

Key:CurrentActive rangeMatchSettledEliminated