#3140
Medium Database Consecutive available seats ii
Database
55.5% acceptance
Mar 31, 2026
13
2
No description available.
Solution
Pandas
Time O(1)
Space O(1)
# 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 ith 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 1:
# 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.
import pandas as pd
def consecutive_available_seats(cinema: pd.DataFrame) -> pd.DataFrame:
cinema = cinema.sort_values('seat_id').reset_index(drop=True)
free = cinema[cinema['free'] == 1]['seat_id'].tolist()
if not free:
return pd.DataFrame(columns=['first_seat_id', 'last_seat_id', 'consecutive_seats_len'])
groups = []
start = free[0]
prev = free[0]
for s in free[1:]:
if s == prev + 1:
prev = s
else:
groups.append((start, prev, prev - start + 1))
start = s
prev = s
groups.append((start, prev, prev - start + 1))
max_len = max(g[2] for g in groups)
result = [(g[0], g[1], g[2]) for g in groups if g[2] == max_len]
return pd.DataFrame(result, columns=['first_seat_id', 'last_seat_id', 'consecutive_seats_len']).sort_values('first_seat_id').reset_index(drop=True)