← Back to SQL, page 14

sql-0268 · Hard senior

Given a table of seats with a taken flag, find runs of at least three adjacent free seats.

Filter to free seats, then apply the islands trick: seat_no - ROW_NUMBER() OVER (ORDER BY seat_no) is constant within a run of adjacent numbers. Group by that key and keep groups with COUNT(*) >= 3, returning the first and last seat of each run.

Full answer
sql
WITH seats(seat_no, taken) AS (VALUES (1,0),(2,0),(3,1),(4,1),(5,0),(6,0),(7,0),(8,0),(9,1),(10,0)),
 free AS (SELECT seat_no, seat_no - ROW_NUMBER() OVER (ORDER BY seat_no) AS grp FROM seats WHERE taken = 0)
SELECT MIN(seat_no) AS first_seat, MAX(seat_no) AS last_seat, COUNT(*) AS seats
FROM free GROUP BY grp HAVING COUNT(*) >= 3;
first_seatlast_seatseats
584

Free seats are 1, 2, 5, 6, 7, 8 and 10. Subtracting the row number gives keys 0, 0, 2, 2, 2, 2 and 3, so the islands are 1 to 2, 5 to 8 and 10 alone. Only 5 to 8 has at least three seats.

For booking, return every possible starting seat for a group of three instead of whole runs:

sql
WITH seats(seat_no, taken) AS (VALUES (1,0),(2,0),(3,1),(4,1),(5,0),(6,0),(7,0),(8,0),(9,1),(10,0)),
 f AS (SELECT seat_no, LEAD(seat_no, 2) OVER (ORDER BY seat_no) AS two_ahead FROM seats WHERE taken = 0)
SELECT seat_no AS start_seat FROM f WHERE two_ahead = seat_no + 2 ORDER BY seat_no;
start_seat
5
6

Seat 5 and seat 6 can each start a block of three. Real seating has rows and aisles, so partition by row and treat an aisle as a break.

sql
WITH seats(seat_no, taken) AS (VALUES (1,0),(2,0),(3,1),(4,1),(5,0),(6,0),(7,0),(8,0),(9,1),(10,0)),
 free AS (SELECT seat_no, seat_no - ROW_NUMBER() OVER (ORDER BY seat_no) AS grp FROM seats WHERE taken = 0)
SELECT MIN(seat_no) AS first_seat, MAX(seat_no) AS last_seat, COUNT(*) AS seats
FROM free GROUP BY grp HAVING COUNT(*) >= 3;

WITH seats(seat_no, taken) AS (VALUES (1,0),(2,0),(3,1),(4,1),(5,0),(6,0),(7,0),(8,0),(9,1),(10,0)),
 f AS (SELECT seat_no, LEAD(seat_no, 2) OVER (ORDER BY seat_no) AS two_ahead FROM seats WHERE taken = 0)
SELECT seat_no AS start_seat FROM f WHERE two_ahead = seat_no + 2 ORDER BY seat_no;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Filter to free seats first
  • seat_no minus ROW_NUMBER identifies adjacent runs
  • Keep runs with at least N seats
  • LEAD(seat, N-1) finds valid starting seats

Common mistakes

  • Applying the trick before filtering out taken seats
  • Ignoring row boundaries in real seating plans

Follow-ups

  • How would you partition by seating row?
  • How would you reserve the seats atomically?

Tips

  • Show the intermediate keys