Corporate Flight Bookings
Medium · Intervals · Array · Prefix Sum
Problem
There are n flights, labeled 1 to n. You are given a list bookings, where bookings[i] = [first, last, seats] reserves seats seats on every flight from first to last, inclusive.
Return an array answer of length n where answer[i] is the total number of seats reserved on flight i + 1.
Examples
Input: bookings = [[1,3,5],[2,4,10]], n = 4 Output: [5,15,15,10]
Flights 2 and 3 are in both bookings; flight 1 only in the first and flight 4 only in the second.
Input: bookings = [[2,2,7]], n = 3 Output: [0,7,0]
Only flight 2 is booked.
Input: bookings = [[1,5,1],[2,4,2],[3,3,4]], n = 5 Output: [1,3,7,3,1]
Each inner range adds to the ranges around it: the middle flight gets 1 + 2 + 4.
Constraints
- 1 <= n <= 2 · 10^4
- 1 <= len(bookings) <= 2 · 10^4
- bookings[i] == [first, last, seats]
- 1 <= first <= last <= n
- 1 <= seats <= 10^4
Approaches
- Baseline: add to every flight in each booking — time O(n · m), space O(n)
Follow-up
The marks-and-running-sum trick is a difference array, and it works for any batch of range updates read once at the end. It shifts letters by ranges just as well (the first use case), and it can decide whether a set of range decrements is enough to wipe out an array (the second). If updates and reads interleave, a Fenwick tree or segment tree does both in O(log n).
Related problems
Start free on Cariara · Coding problems · System design studio