#1109
Corporate Flight Bookings
MediumArrayPrefix SumDifference ArrayPrefix Sum
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach uses a difference array technique to efficiently manage seat counts. This allows us to apply the bookings in constant time and then compute the final seat counts in a single pass.
⚙️
Algorithm
3 steps- 1Step 1: Initialize an array 'answer' of size n with all elements set to 0.
- 2Step 2: For each booking, increment answer[first_i - 1] by seats_i and decrement answer[last_i] by seats_i (if last_i < n).
- 3Step 3: Iterate through the answer array and compute the prefix sum to get the total seats for each flight.
solution.py11 lines
1# Full working Python code
2
3def corpFlightBookings(bookings, n):
4 answer = [0] * (n + 1)
5 for first_i, last_i, seats_i in bookings:
6 answer[first_i - 1] += seats_i
7 if last_i < n:
8 answer[last_i] -= seats_i
9 for i in range(1, n):
10 answer[i] += answer[i - 1]
11 return answer[:-1]ℹ
Complexity note: The time complexity is O(n) because we process each booking in constant time and then compute the prefix sum in a single pass. The space complexity is O(n) due to the additional array used for the difference array technique.
- 1Using a difference array allows for efficient range updates.
- 2Prefix sums can be used to derive final results from incremental changes.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.