Search lands in PR-5.1 (Pagefind).

How-to Intermediate

Chapter 3 Updated

Difference Array

diff[l] += v; diff[r+1] -= v; prefix-sum to recover values.

  • Full 5m
  • Revision
  • Flow

Problem Statement

There are n flights labelled 1 … n. Given a list of bookings where each booking [first, last, seats] reserves seats seats on every flight in [first, last], return an array answer[i] = total seats reserved on flight i.

Input

  • bookings — list of [first, last, seats] triples (1-indexed inclusive range).
  • n — total number of flights.
Example input
bookings = [[1,2,10],[2,3,20],[2,5,25]]
n        = 5

Output

An array of length n where answer[i] = total seats reserved on flight i + 1.

Expected output
[10, 55, 45, 25, 25]

Constraints

  • 1 ≤ n ≤ 2·10⁴
  • 1 ≤ bookings.length ≤ 2·10⁴
  • 1 ≤ firstᵢ ≤ lastᵢ ≤ n
  • 1 ≤ seatsᵢ ≤ 10⁴

Intuition

Naïvely adding seats to every index in [first, last] is O(range) per booking. A difference array converts each update into exactly two O(1) writes: diff[l] += v and diff[r+1] -= v. Prefix-summing the difference array reconstructs the actual values.

Walkthrough — bookings above, n = 5
diff = [0, 0, 0, 0, 0, 0]
 
After [1,2,10]:  [+10,   0, −10,   0,   0,   0]
After [2,3,20]:  [+10, +20, −10, −20,   0,   0]
After [2,5,25]:  [+10, +45, −10, −20,   0, −25]
 
Prefix sum:      [ 10,  55,  45,  25,  25]
                   ↑                    ↑
                  flight 1          flight 5

Solution

corp_flight_bookings.py
def corpFlightBookings(bookings: list[list[int]], n: int) -> list[int]:
    diff = [0] * (n + 1)
    for first, last, seats in bookings:
        diff[first - 1] += seats
        diff[last] -= seats
 
    result, running = [], 0
    for i in range(n):
        running += diff[i]
        result.append(running)
 
    return result

Complexity

MetricValueReason
TimeO(n + m)m updates in O(1) each, plus one linear prefix-sum pass
SpaceO(n)Fixed-size difference array

Edge Case Thinking

ScenarioHandling
Single booking covering all flightsdiff[0] += seats and diff[n] -= seats; prefix sum gives a flat [seats, …].
Overlapping bookingsCombines additively — exactly what the prefix sum produces.
Last booking reaches flight ndiff[last] -= seats is still a valid index because diff is allocated with size n + 1.
Bounded vs unbounded coordinatesDifference array is ideal when coords are bounded; fall back to sweep line for sparse/huge coordinates.
Empty bookingsReturn [0, 0, …] of length n.

Comments

Comments are disabled in this environment. Set PUBLIC_GISCUS_REPO, PUBLIC_GISCUS_REPO_ID, and PUBLIC_GISCUS_CATEGORY_ID to enable.