Given an integer N denoting the number of flights and array bookings[][3] with each row of the form {a, b, K} denoting that there are K seats booked from flight a to flight b ( consider 1-based indexing), the task is to find the sequence of the number of seats booked in N flights.
Examples:
Input: bookings[][] = {{1, 2, 10}, {2, 3, 20}, {2, 5, 25}}
Output: 10 55 45 25 25 Â
Explanation:
Initially, there are no seats booked in any of the flights. So the resultant sequence is {0, 0, 0, 0, 0}
Book 10 seats in flights 1 to 2. The sequence becomes {10, 10, 0, 0, 0}.
Book 20 seats in flights 2 to 3. The sequence becomes {10, 30, 20, 0, 0}.
Book 25 seats in flights 2 to 5. The sequence becomes {10, 55, 45, 25, 25}.Input: bookings[][] = {{1, 3, 100}, {2, 6, 100}, {3, 4, 100}}
Output: 100 200 300 200 100 100
Naive Approach: Follow the steps below to solve the problem in simplest approach possible:
- Initialize an array seq[] of size N to store the count of allocated seats in each flight.
- Traverse the array bookings[].
- For each query {a, b, K}, add the element K in the array seq[] from the index a to b.
- After completing the above steps, print the array seq[] as the result.
Below is the code for the above naive approach :
C++
// C++ program for the naive approachÂ
#include <bits/stdc++.h>using namespace std;Â
// Function to find the total of the// seats booked in each of the flightsvoid corpFlightBookings(vector<vector<int> >& Bookings,                        int N){    // Initialize the array to store the count of    // allocated seats in each flight to zero    vector<int> seq(N, 0);    // Traverse the array    for (int i = 0; i < Bookings.size(); i++) {Â
        // Store the first booked flight        int l = Bookings[i][0];Â
        // Store the last booked flight        int r = Bookings[i][1];Â
        // Store the total number of        // seats booked in flights [l, r]        int K = Bookings[i][2];Â
        // Add K to each flight from L to R        for (int j = l - 1; j < r; j++) {            seq[j] += K;        }    }Â
    // Print the total number of seats    // booked in each flight    for (int i = 0; i < seq.size(); i++) {        cout << seq[i] << " ";    }}Â
// Driver Codeint main(){    // Given list of bookings    vector<vector<int> > bookings{ { 1, 3, 100 },                                   { 2, 6, 100 },                                   { 3, 4, 100 } };    int N = 6;    // Function Call    corpFlightBookings(bookings, N);Â
    return 0;} |
Java
import java.util.ArrayList;import java.util.List;Â
public class CorporateFlightBookings {Â
    // Function to find the total seats booked in each flight    static void corpFlightBookings(List<List<Integer>> bookings, int N) {        // Initialize an array to store the count of allocated seats in each flight to zero        int[] seq = new int[N];Â
        // Traverse the list of bookings        for (List<Integer> booking : bookings) {            // Extract booking information            int l = booking.get(0); // First booked flight            int r = booking.get(1); // Last booked flight            int K = booking.get(2); // Total number of seats bookedÂ
            // Add K to each flight from L to R            for (int j = l - 1; j < r; j++) {                seq[j] += K;            }        }Â
        // Print the total number of seats booked in each flight        for (int i = 0; i < seq.length; i++) {            System.out.print(seq[i] + " ");        }    }Â
    public static void main(String[] args) {        // Given list of bookings        List<List<Integer>> bookings = new ArrayList<>();        bookings.add(List.of(1, 3, 100));        bookings.add(List.of(2, 6, 100));        bookings.add(List.of(3, 4, 100));        int N = 6;Â
        // Function Call        corpFlightBookings(bookings, N);    }} |
Python3
# Function to calculate the total of the# seats booked in each of the flightsdef corpFlightBookings(bookings, N):    # Initialize the array to store the count of    # allocated seats in each flight to zero    seq = [0] * NÂ
    # Traverse the list of bookings    for i in range(len(bookings)):        # Store the first booked flight        l = bookings[i][0]Â
        # Store the last booked flight        r = bookings[i][1]Â
        # Store the total number of seats booked in flights [l, r]        K = bookings[i][2]Â
        # Add K to each flight from L to R        for j in range(l - 1, r):            seq[j] += KÂ
    # Print the total number of seats booked in each flight    for i in range(len(seq)):        print(seq[i], end=" ")Â
# Driver Codeif __name__ == "__main__":    #list of bookings    bookings = [[1, 3, 100],                [2, 6, 100],                [3, 4, 100]]    N = 6    corpFlightBookings(bookings, N) |
C#
using System;using System.Collections.Generic;Â
class Program{    // Function to find the total of the seats booked in each of the flights    static void CorpFlightBookings(List<List<int>> bookings, int N)    {        // Initialize the array to store the count of allocated seats in each flight to zero        int[] seq = new int[N];Â
        // Traverse the list of bookings        foreach (var booking in bookings)        {            // Store the first booked flight            int l = booking[0];Â
            // Store the last booked flight            int r = booking[1];Â
            // Store the total number of seats booked in flights [l, r]            int K = booking[2];Â
            // Add K to each flight from L to R            for (int j = l - 1; j < r; j++)            {                seq[j] += K;            }        }Â
        // Print the total number of seats booked in each flight        for (int i = 0; i < seq.Length; i++)        {            Console.Write(seq[i] + " ");        }    }Â
    static void Main()    {        // Given list of bookings        List<List<int>> bookings = new List<List<int>>        {            new List<int> {1, 3, 100},            new List<int> {2, 6, 100},            new List<int> {3, 4, 100}        };        int N = 6;Â
        // Function Call        CorpFlightBookings(bookings, N);    }} |
100 200 300 200 100 100
Time Complexity: O(N2)
Auxiliary Space: O(N)
Efficient Approach: To optimize the above approach, the idea is to use the concept of Prefix Sum. Follow the steps below to solve the problem:
- Initialize an array seq[] of size (N + 2) to store all the allocated seats.
- Traverse the array bookings[].
- For each query {a, b, K}, increment the array seq[] at index (a – 1) by K and decrement the element at index (b + 1) by K.
- For the resulting sequence, find the prefix sum of the array seq[].
- After completing the above steps, print the array seq[] as the result.
Below is the implementation of the above approach:
C++
// C++ program for the above approachÂ
#include <bits/stdc++.h>using namespace std;Â
// Function to find the total of the// seats booked in each of the flightsvoid corpFlightBookings(    vector<vector<int> >& Bookings,    int N){    // Stores the resultant sequence    vector<int> res(N, 0);Â
    // Traverse the array    for (int i = 0;         i < Bookings.size(); i++) {Â
        // Store the first booked flight        int l = Bookings[i][0];Â
        // Store the last booked flight        int r = Bookings[i][1];Â
        // Store the total number of        // seats booked in flights [l, r]        int K = Bookings[i][2];Â
        // Add K to the flight L        res[l - 1] = res[l - 1] + K;Â
        // Subtract K from flight        // number R + 1        if (r <= res.size() - 1)            res[r] = (-K) + res[r];    }Â
    // Find the prefix sum of the array    for (int i = 1; i < res.size(); i++)        res[i] = res[i] + res[i - 1];Â
    // Print the total number of seats    // booked in each flight    for (int i = 0; i < res.size(); i++) {        cout << res[i] << " ";    }}Â
// Driver Codeint main(){    // Given list of bookings    vector<vector<int> > bookings{ { 1, 3, 100 },                                   { 2, 6, 100 },                                   { 3, 4, 100 } };    int N = 6;Â
    // Function Call    corpFlightBookings(bookings, N);Â
    return 0;} |
Java
// Java program for the above approachimport java.util.*;Â
class GFG{Â
// Function to find the total of the// seats booked in each of the flightsstatic void corpFlightBookings(int [][]Bookings,                               int N){       // Stores the resultant sequence    int res[] = new int[N];Â
    // Traverse the array    for (int i = 0;         i < Bookings.length; i++)    {Â
        // Store the first booked flight        int l = Bookings[i][0];Â
        // Store the last booked flight        int r = Bookings[i][1];Â
        // Store the total number of        // seats booked in flights [l, r]        int K = Bookings[i][2];Â
        // Add K to the flight L        res[l - 1] = res[l - 1] + K;Â
        // Subtract K from flight        // number R + 1        if (r <= res.length - 1)            res[r] = (-K) + res[r];    }Â
    // Find the prefix sum of the array    for (int i = 1; i < res.length; i++)        res[i] = res[i] + res[i - 1];Â
    // Print the total number of seats    // booked in each flight    for (int i = 0; i < res.length; i++)    {        System.out.print(res[i] + " ");    }}Â
// Driver Codepublic static void main(String[] args){       // Given list of bookings    int bookings[][] = { { 1, 3, 100 },                        { 2, 6, 100 },                        { 3, 4, 100 } };    int N = 6;Â
    // Function Call    corpFlightBookings(bookings, N);}}Â
// This code is contributed by 29AjayKumar |
Python3
# Python3 program for the above approachÂ
# Function to find the total of the# seats booked in each of the flightsdef corpFlightBookings(Bookings, N):       # Stores the resultant sequence    res = [0] * NÂ
    # Traverse the array    for i in range(len(Bookings)):Â
        # Store the first booked flight        l = Bookings[i][0]Â
        # Store the last booked flight        r = Bookings[i][1]Â
        # Store the total number of        # seats booked in flights [l, r]        K = Bookings[i][2]Â
        # Add K to the flight L        res[l - 1] = res[l - 1] + KÂ
        # Subtract K from flight        # number R + 1        if (r <= len(res) - 1):            res[r] = (-K) + res[r]Â
    # Find the prefix sum of the array    for i in range(1, len(res)):        res[i] = res[i] + res[i - 1]Â
    # Print total number of seats    # booked in each flight    for i in range(len(res)):        print(res[i], end = " ")Â
# Driver Codeif __name__ == '__main__':       # Given list of bookings    bookings = [ [ 1, 3, 100 ],               [ 2, 6, 100 ],               [ 3, 4, 100 ] ]    N = 6Â
    # Function Call    corpFlightBookings(bookings, N)Â
# This code is contributed by mohit kumar 29 |
C#
// C# program for the above approachusing System;class GFG{Â
// Function to find the total of the// seats booked in each of the flightsstatic void corpFlightBookings(int [,]Bookings,                               int N){       // Stores the resultant sequence    int []res = new int[N];Â
    // Traverse the array    for (int i = 0;         i < Bookings.GetLength(0); i++)    {Â
        // Store the first booked flight        int l = Bookings[i,0];Â
        // Store the last booked flight        int r = Bookings[i,1];Â
        // Store the total number of        // seats booked in flights [l, r]        int K = Bookings[i,2];Â
        // Add K to the flight L        res[l - 1] = res[l - 1] + K;Â
        // Subtract K from flight        // number R + 1        if (r <= res.Length - 1)            res[r] = (-K) + res[r];    }Â
    // Find the prefix sum of the array    for (int i = 1; i < res.Length; i++)        res[i] = res[i] + res[i - 1];Â
    // Print the total number of seats    // booked in each flight    for (int i = 0; i < res.Length; i++)    {        Console.Write(res[i] + " ");    }}Â
// Driver Codepublic static void Main(String[] args){       // Given list of bookings    int [,]bookings = { { 1, 3, 100 },                        { 2, 6, 100 },                        { 3, 4, 100 } };    int N = 6;Â
    // Function Call    corpFlightBookings(bookings, N);}}Â
// This code is contributed by shikhasingrajput |
Javascript
<script>Â
// Javascript program for the above approachÂ
// Function to find the total of the// seats booked in each of the flightsfunction corpFlightBookings(Bookings, N){         // Stores the resultant sequence    let res = new Array(N).fill(0);Â
    // Traverse the array    for(let i = 0;            i < Bookings.length; i++)    {                 // Store the first booked flight        let l = Bookings[i][0];Â
        // Store the last booked flight        let r = Bookings[i][1];Â
        // Store the total number of        // seats booked in flights [l, r]        let K = Bookings[i][2];Â
        // Add K to the flight L        res[l - 1] = res[l - 1] + K;Â
        // Subtract K from flight        // number R + 1        if (r <= res.length - 1)            res[r] = (-K) + res[r];    }Â
    // Find the prefix sum of the array    for(let i = 1; i < res.length; i++)        res[i] = res[i] + res[i - 1];Â
    // Print the total number of seats    // booked in each flight    for(let i = 0; i < res.length; i++)    {        document.write(res[i] + " ");    }}Â
// Driver CodeÂ
// Given list of bookingslet bookings = [ [ 1, 3, 100 ],                 [ 2, 6, 100 ],                 [ 3, 4, 100 ] ];let N = 6;Â
// Function CallcorpFlightBookings(bookings, N);Â
// This code is contributed by splevel62Â
</script> |
100 200 300 200 100 100
Time Complexity: O(N)
Auxiliary Space: O(N)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!
