Consecutive Available Seats — LeetCode 603 Python Solution

EasyLeetCode PremiumDatabase
Problem
#603
Reading time
2 min

The problem

Report the ids of the free seats that sit next to at least one other free seat, ordered by seat id. The Cinema table has one row per seat: seat_id (int, an auto-increment column) and free (bool, where 1 means free and 0 means occupied).

Example

Cinema table:

| seat_id | free |
| ------- | ---- |
| 1       | 1    |
| 2       | 0    |
| 3       | 1    |
| 4       | 1    |
| 5       | 1    |

Result:

| seat_id |
| ------- |
| 3       |
| 4       |
| 5       |

Seats 3, 4 and 5 form a free block, while seat 1 is free but its only neighbour, seat 2, is taken.

Python solution

Python
import pandas as pd

def consecutive_available_seats(cinema: pd.DataFrame) -> pd.DataFrame:
    free = cinema[cinema['free'] == 1]
    free_ids = set(free['seat_id'])
    res = free[free['seat_id'].apply(lambda x: (x - 1 in free_ids) or (x + 1 in free_ids))]
    return res[['seat_id']].sort_values('seat_id')

Complexity

MeasureComplexity
TimeO(n log n) (typical)
SpaceO(n) auxiliary

Related problems

Frequently asked questions

How hard is LeetCode 603. Consecutive Available Seats?
LeetCode 603. Consecutive Available Seats is rated Easy on LeetCode.
What topics does LeetCode 603. Consecutive Available Seats cover?
LeetCode 603. Consecutive Available Seats is tagged Database on LeetCode.
Is LeetCode 603. Consecutive Available Seats a premium problem?
Yes. LeetCode 603. Consecutive Available Seats is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview