Leetcode 1109: Corporate Flight Bookings

grid47
grid47
Exploring patterns and algorithms
Jul 19, 2024 6 min read

You are given a list of flight bookings, where each booking specifies the flight range (from first flight to last flight) and the number of seats reserved for each of the flights in that range. You need to compute the total number of seats reserved for each flight, from flight 1 to flight n.
Problem
Approach
Steps
Complexity
Input: You are given a list of bookings, where each element `bookings[i]` is an array containing three integers: `[firsti, lasti, seatsi]`, representing the first flight, last flight, and the number of seats reserved for each flight in the given range. Additionally, you are given an integer `n` representing the total number of flights.
Example: bookings = [[1, 2, 10], [2, 3, 20], [2, 5, 25]], n = 5
Constraints:
• 1 <= n <= 2 * 10^4
• 1 <= bookings.length <= 2 * 10^4
• bookings[i].length == 3
• 1 <= firsti <= lasti <= n
• 1 <= seatsi <= 10^4
Output: Return an array `answer` of length `n`, where each element `answer[i]` represents the total number of seats reserved for the i-th flight.
Example: Output: [10, 55, 45, 25, 25]
Constraints:
• Each element in the answer array should be the sum of reserved seats for the respective flight.
Goal: The goal is to calculate the total number of reserved seats for each flight while efficiently handling multiple bookings that affect overlapping flight ranges.
Steps:
• Start with an array `ans` initialized to zero, which will store the total seats for each flight.
• For each booking, increment the number of seats reserved for the first flight in the range, and decrement the number of seats for the flight right after the last flight in the range.
• Use a cumulative sum to calculate the total seats reserved for each flight.
Goal: Efficient handling of bookings and the large input constraints is crucial to the solution.
Steps:
• Bookings are guaranteed to follow the input constraints, such as 1 <= firsti <= lasti <= n.
Assumptions:
• Each flight range will contain valid indexes and the number of seats will always be within the allowed range.
Input: Input: bookings = [[1, 2, 10], [2, 3, 20], [2, 5, 25]], n = 5
Explanation: In this case, bookings affect the following flights: the first booking reserves 10 seats for flights 1 and 2. The second booking reserves 20 seats for flights 2 and 3. The third booking reserves 25 seats for flights 2 through 5. The total seats for each flight are: [10, 55, 45, 25, 25].

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus