+-------------+------+
|Column Name |Type|+-------------+------+
| seat_id | int ||free| bool |+-------------+------+
seat_id is an auto-incrementcolumnfor this table.
Eachrowof this table indicates whether the ith seat isfreeornot. 1 means free while 0 means occupied.
Write a solution to find the length of longest consecutive sequence of available seats in the cinema.
Note:
There will always be at mostone longest consecutive sequence.
If there are multiple consecutive sequences with the same length , include all of them in the output.
Return the result tableordered byfirst_seat_idin ascending order.
Input:
Cinema table:+---------+------+| seat_id | free |+---------+------+|1|1||2|0||3|1||4|1||5|1|+---------+------+Output:
+-----------------+----------------+-----------------------+| first_seat_id | last_seat_id | consecutive_seats_len |+-----------------+----------------+-----------------------+|3|5|3|+-----------------+----------------+-----------------------+Explanation:
* Longest consecutive sequence of available seats starts from seat 3 and ends at seat 5with a length of 3.Output table is ordered by first_seat_id in ascending order.
We want to find the length of the longest consecutive sequence of available seats (free = 1). We can use window functions to assign a group number to each consecutive block of free seats, then count the length of each group and select the maximum.
Use a window function to assign a group number to each consecutive block of free seats. This can be done by subtracting the row number from the seat_id for free seats.
Filter only free seats (free = 1).
Group by the group number and count the number of seats in each group.
Find the maximum length among all groups.
If there are multiple groups with the same maximum length, include all of them in the output.
WITH free_seats AS (
SELECT seat_id, free,
seat_id -ROW_NUMBER() OVER (ORDERBY seat_id) AS grp
FROM Cinema
WHERE free =1)
SELECTCOUNT(*) AS length
FROM free_seats
GROUPBY grp
HAVINGCOUNT(*) = (
SELECTMAX(cnt) FROM (
SELECTCOUNT(*) AS cnt FROM free_seats GROUPBY grp
) t
);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
WITH free_seats AS (
SELECT seat_id, free,
seat_id - ROW_NUMBER() OVER (ORDERBY seat_id) AS grp
FROM Cinema
WHERE free =1)
SELECT COUNT(*) AS length
FROM free_seats
GROUPBY grp
HAVING COUNT(*) = (
SELECT MAX(cnt) FROM (
SELECT COUNT(*) AS cnt FROM free_seats GROUPBY grp
) t
);