+-------------------+------+
|Column Name |Type|+-------------------+------+
| departure_airport | int || arrival_airport | int || flights_count | int |+-------------------+------+
(departure_airport, arrival_airport) is the primarykeycolumn (combination of columns withuniquevalues) for this table.
Eachrowof this table indicates that there were flights_count flights that departed from departure_airport and arrived at arrival_airport.
Write a solution to report the ID of the airport with the most traffic.
The airport with the most traffic is the airport that has the largest total number of flights that either departed from or arrived at the airport. If there is more than one airport with the most traffic, report them all.
Total traffic for an airport equals the sum of flights that departed from it plus the flights that arrived to it. We can compute per-airport totals by summing flights_count twice: once treating departure_airport as airport_id and once treating arrival_airport as airport_id, then grouping by airport_id.
SELECT airport_id
FROM (
SELECT airport_id, SUM(flights_count) AS total_traffic
FROM (
SELECT departure_airport AS airport_id, flights_count FROM Flights
UNIONALLSELECT arrival_airport AS airport_id, flights_count FROM Flights
) t
GROUPBY airport_id
) s
WHERE total_traffic = (
SELECTMAX(total_traffic) FROM (
SELECT airport_id, SUM(flights_count) AS total_traffic
FROM (
SELECT departure_airport AS airport_id, flights_count FROM Flights
UNIONALLSELECT arrival_airport AS airport_id, flights_count FROM Flights
) t
GROUPBY airport_id
) x
);
SELECT airport_id
FROM (
SELECT airport_id, SUM(flights_count) AS total_traffic
FROM (
SELECT departure_airport AS airport_id, flights_count FROM Flights
UNIONALLSELECT arrival_airport AS airport_id, flights_count FROM Flights
) t
GROUPBY airport_id
)
WHERE total_traffic = (
SELECTMAX(total_traffic) FROM (
SELECT airport_id, SUM(flights_count) AS total_traffic
FROM (
SELECT departure_airport AS airport_id, flights_count FROM Flights
UNIONALLSELECT arrival_airport AS airport_id, flights_count FROM Flights
) t
GROUPBY airport_id
) x
);
1
2
3
4
5
6
7
8
9
10
11
12
WITH airport_traffic AS (
SELECT airport_id, SUM(flights_count) AS total_traffic
FROM (
SELECT departure_airport AS airport_id, flights_count FROM Flights
UNIONALLSELECT arrival_airport AS airport_id, flights_count FROM Flights
) t
GROUPBY airport_id
)
SELECT airport_id
FROM airport_traffic
WHERE total_traffic = (SELECTMAX(total_traffic) FROM airport_traffic);
⏰ Time complexity:O(N) – We scan the Flights table a constant number of times and perform grouping/aggregation over the resulting rows (N = number of flight records).
🧺 Space complexity:O(M) – We store aggregated traffic per airport (M = number of distinct airports).