Corporate Flight Bookings - Problem

There are n flights that are labeled from 1 to n.

You are given an array of flight bookings bookings, where bookings[i] = [first_i, last_i, seats_i] represents a booking for flights first_i through last_i (inclusive) with seats_i seats reserved for each flight in the range.

Return an array answer of length n, where answer[i] is the total number of seats reserved for flight i.

Input & Output

Example 1 — Basic Overlapping Bookings
$ Input: bookings = [[1,2,10],[2,3,20],[2,5,25]], n = 5
Output: [10,55,45,25,25]
💡 Note: Flight 1: 10 seats from [1,2,10]. Flight 2: 10+20+25=55 seats (all three bookings cover flight 2). Flight 3: 20+25=45 seats. Flights 4,5: 25 seats each from [2,5,25].
Example 2 — Single Booking
$ Input: bookings = [[1,2,10]], n = 2
Output: [10,10]
💡 Note: One booking [1,2,10] covers flights 1 and 2, so both get 10 seats.
Example 3 — Non-overlapping Ranges
$ Input: bookings = [[1,2,10],[3,4,20]], n = 4
Output: [10,10,20,20]
💡 Note: First booking covers flights 1-2 with 10 seats each. Second booking covers flights 3-4 with 20 seats each. No overlap.

Constraints

  • 1 ≤ n ≤ 2 × 104
  • 1 ≤ bookings.length ≤ 2 × 104
  • bookings[i].length == 3
  • 1 ≤ firsti ≤ lasti ≤ n
  • 1 ≤ seatsi ≤ 104

Visualization

Tap to expand
Corporate Flight Bookings INPUT bookings array (n=5 flights) [1, 2, 10] Flights 1-2: 10 seats each [2, 3, 20] Flights 2-3: 20 seats each [2, 5, 25] Flights 2-5: 25 seats each Flights 1 to 5: F1 F2 F3 F4 F5 Input Values: bookings = [[1,2,10], [2,3,20],[2,5,25]] ALGORITHM STEPS 1 Init Diff Array diff[0..5] = [0,0,0,0,0,0] 2 Apply Difference diff[first-1] += seats diff[last] -= seats 3 Process Bookings Mark start/end of ranges Difference Array Changes: [1,2,10]: +10 at 0, -10 at 2 [2,3,20]: +20 at 1, -20 at 3 [2,5,25]: +25 at 1, -25 at 5 diff=[10,45,-10,-20,0,-25] (index 0-5) 4 Prefix Sum Cumulate to get seats 10-->55-->45-->25-->25 (running sum for flights 1-5) FINAL RESULT Total seats per flight: F1 10 F2 55 F3 45 F4 25 F5 25 Seat Breakdown: F1: 10 (from booking 1) F2: 10+20+25 = 55 F3: 20+25 = 45 F4: 25 (from booking 3) F5: 25 (from booking 3) All ranges covered correctly! Output: [10, 55, 45, 25, 25] OK - Verified! Key Insight: Use Difference Array technique: Instead of updating each flight in range (O(n) per booking), mark only start (+seats) and end+1 (-seats) positions. Final prefix sum gives total seats. Time: O(n + bookings) | Space: O(n) -- Optimal! TutorialsPoint - Corporate Flight Bookings | Optimal Solution (Difference Array)
Asked in
Amazon 15 Google 12 Microsoft 8
28.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen