Theater seat finder
def free_per_row(rows), def find_block(rows, k, spaced=False)A theater seat map is a list of strings, front row first. 'X' is a taken seat and '.' is a free seat.
- Part 1. Write free_per_row(rows), which returns the number of free seats in each row.
- Part 2. Write find_block(rows, k), which returns [row, col] for the first block of k free seats side by side, searching front to back and left to right, or None if there is none.
- Part 3. Now the group wants space. With spaced=True, find the first block of k free seats where the seat just left of the block and the seat just right of it are also free, or are the edge of the row.
Example
- Input
rows = ["X..X...", "....XX.", "X......"] free_per_row(rows) find_block(rows, 3) find_block(rows, 3, spaced=True)
- Output
[5, 5, 6] [0, 4] [1, 0]
- Why
- The block at row 0, col 4 has a taken seat on its left, so the spaced search moves on to row 1, where the block touches the row's left edge.
Show approach and solution
Say this out loud
- Say out loud that "first" means front to back, then left to right.
- Ask whether an aisle splits a row. Here each row is one straight line.
- The slice check is O(k) per position; mention that a running count of free seats would make it O(rows x cols).
Approach
Part 1 counts dots per row. Parts 2 and 3 try every starting column in every row, check that the next k seats are free, and for the spaced version also check the seat on each side (or the edge). The first match is returned.
def free_per_row(rows):
return [row.count('.') for row in rows]
def find_block(rows, k, spaced=False):
for r, row in enumerate(rows):
for c in range(len(row) - k + 1):
if row[c:c + k] != '.' * k:
continue
if spaced:
left_ok = c == 0 or row[c - 1] == '.'
right_ok = c + k == len(row) or row[c + k] == '.'
if not (left_ok and right_ok):
continue
return [r, c]
return NoneComplexity: O(rows x cols x k) time as written, O(1) extra space.
What the interviewer will look for: k larger than the row, k = 1, a block touching the row's edge, rows that are all taken, and returning None when nothing fits.
