Consecutive Available Seats II Problem
#3140
Description
LeetCode Problem 3140.
Table: Cinema
+-------------+------+
| Column Name | Type |
+-------------+------+
| seat_id | int |
| free | bool |
+-------------+------+
seat_id is an auto-increment column for this table.
Each row of this table indicates whether the i^th seat is free or not. 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 most one longest consecutive sequence.
- If there are multiple consecutive sequences with the same length, include all of them in the output.
Return the result table ordered by first_seat_id in ascending order.
The result format is in the following example.
Example:
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 5 with a length of 3.
Output table is ordered by first_seat_id in ascending order.
Solution
Approach: Group free seats by seat_id minus rank
This is the classic "islands" problem. Among the free seats, seat_id grows by one inside a run of consecutive seats, and so does the row number, so their difference stays constant for the whole run and changes when a gap appears.
- Keep only free seats and compute
seat_id - ROW_NUMBER() OVER (ORDER BY seat_id). Every run of consecutive seats gets its own constant value. - Group by that value to get each run's first seat, last seat and length.
- Keep the runs whose length equals the maximum length. Several runs may tie, and all of them are returned, ordered by the first seat.
Using the window MAX(len) OVER () avoids a second scan. Pandas follows the same steps with groupby on the difference.
WITH free_seats AS (
SELECT seat_id,
seat_id - ROW_NUMBER() OVER (ORDER BY seat_id) AS grp
FROM Cinema
WHERE free = 1
),
runs AS (
SELECT MIN(seat_id) AS first_seat_id,
MAX(seat_id) AS last_seat_id,
COUNT(*) AS consecutive_seats_len
FROM free_seats
GROUP BY grp
)
SELECT first_seat_id, last_seat_id, consecutive_seats_len
FROM (
SELECT *, MAX(consecutive_seats_len) OVER () AS longest
FROM runs
) AS t
WHERE consecutive_seats_len = longest
ORDER BY first_seat_id;