Python 1109.py
class Solution:
def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:
# min-heap based on "first"
departure = []
for b in bookings:
departure.append(( b ))
heapify(departure)
# min-heap based on "last"
active = []
seats = 0
for i in range(1, n + 1):
# starting on current day
while departure and departure[0][0] == i:
add = heappop(departure)
heappush(active, ( add[1], add[2] ))
seats += add[2]
yield seats
# arriving on current day
while active and active[0][0] == i:
remove = heappop(active)
seats -= remove[1]
Difficulty
and has an acceptance rate of about 67% (100k+ submissions).
Typical patterns to solve this problem:
- Array
- Prefix Sum
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a Solution class with a method corpFlightBookings that processes a collection of flight booking intervals and produces a running total of seats occupied for each day from 1 to n. The algorithm relies on two min-heaps: one to track the start of each booking interval and another to manage the active bookings that have begun but not yet ended. By incrementally advancing day by day, the method updates the seat count as bookings start and finish, yielding the cumulative seats for each day.
Key Steps
The first major step constructs a heap that orders bookings by their start day. The code extracts each booking tuple from the input list and pushes it onto the departure heap, then calls heapify to enforce heap order.
departure = []
for b in bookings:
departure.append(( b ))
heapify(departure)
Next, an empty heap named active is prepared to hold bookings that are currently in effect, keyed by their end day. A variable seats is initialized to zero to accumulate the total seats for the current day.
active = []
seats = 0
The core loop iterates over each day index i from 1 through n. Within this loop, the algorithm first extracts all bookings whose start day matches the current day. For each such booking, it removes the entry from departure, pushes a tuple containing the booking’s end day and seat count onto active, and adds the seat count to seats.
while departure and departure[0][0] == i:
add = heappop(departure)
heappush(active, ( add[1], add[2] ))
seats += add[2]
After processing new arrivals, the method yields the current seat total, allowing the caller to collect the daily seat counts lazily.
yield seats
Finally, the loop removes any bookings that conclude on the current day. It repeatedly pops from active while the smallest end day equals i, subtracting the corresponding seat count from seats.
while active and active[0][0] == i:
remove = heappop(active)
seats -= remove[1]
The combination of these steps ensures that seats always reflects the sum of seats for bookings that span the current day.
Edge Cases
The algorithm gracefully handles the situation where no bookings start on a particular day; the first while loop simply bypasses execution, leaving seats unchanged for that iteration. Similarly, if no active bookings end on a given day, the second while loop does nothing, preserving the accumulated seat count. When multiple bookings share the same start day, the first loop extracts each one in turn, correctly aggregating their seat contributions before yielding the total. The same logic applies to multiple bookings ending on the same day, ensuring that all relevant seat reductions are applied before the next day begins. If the input bookings list is empty, the departure heap remains empty, the loops never execute, and the method yields a sequence of zeros for all n days.
Performance Optimizations
The use of two min-heaps provides an efficient way to access the next booking start and the next booking end without scanning the entire list of bookings on each day. By maintaining the heaps in sorted order, the algorithm performs insertion and removal operations in logarithmic time relative to the number of active intervals, which reduces the overall work compared to a naïve per-day scan. The heapify call on the initial departure list builds the heap in linear time, preparing the structure for fast subsequent heappop operations. Yielding results incrementally rather than constructing a full list up front allows the caller to consume the output lazily, which can save memory when only a portion of the result is needed. The separation of concerns-one heap for upcoming starts and another for ongoing intervals-prevents unnecessary checks and keeps each heap’s size bounded by the number of bookings that are currently relevant, further contributing to efficient execution.
ELI5 - Simplified Explanation
Imagine a train that travels through many different stations. The goal is to keep track of how many people are sitting on the train at each station. There is a list of trips that tells exactly when each group of passengers gets on the train and when they get off.
The computer creates two special piles to keep things organized. The first pile holds all the groups that are waiting to start their journey. Every time the train arrives at a new station, the computer checks this pile to see if anyone is waiting there to get on. If a group is ready, they hop on the train and the number of seats being used goes up.
While the train travels, the computer also keeps a second pile for the people who are already on the train. This pile remembers exactly when each group plans to leave. As soon as the train stops at a station where a group is finished with their trip, the computer takes them off the train and the number of seats being used goes back down.
This process happens for every single station from the beginning of the trip until the very end. At each stop, the computer looks at the piles, updates how many seats are taken, and writes down the total number of happy travelers currently on board.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||
| WalkCCC | C++ | Python | Java | ||||||
| leetcode.ca | C++ | Python | JS | Java | Go | Rust | |||
| Progiez | C++ | Python | Java | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| wisdompeak | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python, Rust | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| wisdompeak | C++ |
Videos
Solved On The Same Day
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality