Taro Logo

Cinema Seat Allocation

#2 Most AskedMedium
1 view
Topics:
ArraysGreedy AlgorithmsBit Manipulation

A cinema has n rows of seats, numbered from 1 to n and there are ten seats in each row, labelled from 1 to 10 as shown in the figure above.

Given the array reservedSeats containing the numbers of seats already reserved, for example, reservedSeats[i] = [3,8] means the seat located in row 3 and labelled with 8 is already reserved.

Return the maximum number of four-person groups you can assign on the cinema seats. A four-person group occupies four adjacent seats in one single row. Seats across an aisle (such as [3,3] and [3,4]) are not considered to be adjacent, but there is an exceptional case on which an aisle split a four-person group, in that case, the aisle split a four-person group in the middle, which means to have two people on each side.

Example 1:

Input: n = 3, reservedSeats = [[1,2],[1,3],[1,8],[2,6],[3,1],[3,10]]
Output: 4
Explanation: The figure above shows the optimal allocation for four groups, where seats mark with blue are already reserved and contiguous seats mark with orange are for one group.

Example 2:

Input: n = 2, reservedSeats = [[2,1],[1,8],[2,6]]
Output: 2

Example 3:

Input: n = 4, reservedSeats = [[4,3],[1,4],[4,6],[1,7]]
Output: 4

Constraints:

  • 1 <= n <= 10^9
  • 1 <= reservedSeats.length <= min(10*n, 10^4)
  • reservedSeats[i].length == 2
  • 1 <= reservedSeats[i][0] <= n
  • 1 <= reservedSeats[i][1] <= 10
  • All reservedSeats[i] are distinct.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the maximum number of rows ($n$), and what is the maximum size of the reserved seats list?
  2. Can the list of reserved seats contain duplicate entries, or are all provided seat coordinates guaranteed to be unique?
  3. Are there any specific constraints or behaviors we need to consider if a row has zero reserved seats versus all seats reserved?
  4. Can the reserved seats list contain invalid seat numbers (e.g., column numbers less than 1 or greater than 10, or row numbers exceeding $n$)?
  5. Should rows that have no reserved seats explicitly appear in the input, or do we assume unlisted rows are completely empty/available?

Brute Force Solution

Approach

Imagine you need to figure out the maximum number of families of four that can sit together in a movie theater with some seats already taken. The brute force approach involves looking at every single row in the cinema one by one and manually testing every possible spot where a family of four could sit.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the very first row of the cinema and noting which seats are already taken by other people.
  2. Check the left side of the row to see if a group of four people can sit together without overlapping any taken seats.
  3. Check the middle section of the row to see if a group of four can sit together there.
  4. Check the right side of the row to see if a group of four can sit together there.
  5. Count how many valid groups of four you found in this row, making sure the same seat is not counted twice.
  6. Move on to the next row in the cinema and repeat the exact same checking process for the left, middle, and right sections.
  7. Continue this check for every single row in the theater until you have visited all of them.
  8. Add up all the valid groups of four you found across every row to get the final total number of families that can be seated.

Code Implementation

def max_number_of_families(row_count, reserved_seats):
    # Group reserved seats by row to check each row independently and efficiently
    row_to_reserved_map = {}
    for seat_position in reserved_seats:
        row_number = seat_position[0]
        seat_number = seat_position[1]
        if row_number not in row_to_reserved_map:
            row_to_reserved_map[row_number] = set()
        row_to_reserved_map[row_number].add(seat_number)

    total_families_seated = 0
    
    # Iterate through every possible row in the theater to evaluate seating options
    for current_row in range(1, row_count + 1):
        reserved_in_row = row_to_reserved_map.get(current_row, set())
        families_in_current_row = 0

        can_sit_left = not any(seat in reserved_in_row for seat in [2, 3, 4, 5])
        can_sit_right = not any(seat in reserved_in_row for seat in [6, 7, 8, 9])
        can_sit_middle = not any(seat in reserved_in_row for seat in [4, 5, 6, 7])

        # Count maximum non-overlapping families of four that can fit into the row
        if can_sit_left:
            families_in_current_row += 1
        if can_sit_right:
            families_in_current_row += 1
        if not can_sit_left and not can_sit_right and can_sit_middle:
            families_in_current_row += 1

        total_families_seated += families_in_current_row

    # Include rows with no reservations since they can always seat the maximum possible families
    unreserved_rows_count = row_count - len(row_to_reserved_map)
    total_families_seated += unreserved_rows_count * 2

    return total_families_seated

Big(O) Analysis

Time Complexity
O(n) – To find the maximum number of families, we process the reserved seats and iterate through at most n unique rows in the cinema. For each row, we perform a constant number of bitwise checks to evaluate the left, middle, and right sections for seating availability. Since we only loop through the number of rows n, the total operations scale linearly as a constant multiple of n. This simplifies to a final Big O time complexity of O(n).
Space Complexity
O(R) – To efficiently check seat allocations, we use a hash map or dictionary to store the status of the reserved seats, where R represents the number of rows that have at least one reserved seat. In the worst-case scenario where every single row has at least one reservation, this hash map will store up to R entries. Therefore, the auxiliary space scales directly with the number of affected rows R, leading to a space complexity of O(R).

Optimal Solution

Approach

Instead of checking every single seat combination for every row one by one, the optimal approach focuses only on the rows where people have actually reserved seats. For each of these special rows, it looks at specific blocks of seats to see which family groupings can fit.

Here's how the algorithm would work step-by-step:

  1. Make a list of only the rows that contain at least one reserved seat, ignoring completely empty rows for now because they are easy to calculate at the very end.
  2. For each row in your special list, check which specific groups of four seats are blocked by any reservations.
  3. Determine if a family can sit in the left block of four seats, the right block of four seats, or the middle overlapping block of four seats.
  4. Count how many non-overlapping family groups can fit into the current row based on the remaining open seats.
  5. Add up these family counts for all the rows that had reservations.
  6. For any rows that had zero reservations, calculate the maximum possible number of families that can fit by simply multiplying the number of completely empty rows by two.
  7. Combine the total families from the reserved rows and the completely empty rows to get the final answer.

Code Implementation

def maxNumberOfFamilies(row_count, reserved_seats):

    row_to_reservations = {}

    for row_number, seat_number in reserved_seats:

        if row_number not in row_to_reservations:

            row_to_reservations[row_number] = set()

        row_to_reservations[row_number].add(seat_number)


    # Grouping by row avoids processing empty rows individually to optimize performance.
    total_families = (row_count - len(row_to_reservations)) * 2


    for current_row, reserved_set in row_to_reservations.items():

        left_blocked = any(seat in reserved_set for seat in [2, 3, 4, 5])

        right_blocked = any(seat in reserved_set for seat in [6, 7, 8, 9])

        middle_blocked = any(seat in reserved_set for seat in [4, 5, 6, 7])


        # Checking overlapping blocks determines if one or two family groups can fit.
        if not left_blocked and not right_blocked:

            total_families += 2

        elif not left_blocked or not right_blocked or not middle_blocked:

            total_families += 1


    # Summing calculated rows with empty rows yields the final maximum capacity.
    return total_families

Big(O) Analysis

Time Complexity
O(r) – The primary driver of the time complexity is the number of rows with reserved seats, let us call this r, which is at most the total number of rows n or twice the number of reservations. We iterate through the list of reserved seats once to group them by row, and then iterate through each of the r special rows to perform a constant number of bitwise or hash-based checks for the three possible family blocks. Finally, calculating the capacity for the remaining completely empty rows takes constant time. Because these steps scale linearly with the number of rows containing reservations, the total operations approximate r plus n, which simplifies to O(n).
Space Complexity
O(R) – To implement step 1 and step 2, we use an auxiliary hash map or dictionary to group the reserved seats by their specific row numbers, where R represents the number of rows with at least one reservation. This data structure stores at most all the reserved seat inputs, meaning the memory footprint scales directly with the number of rows containing reserved seats. As the number of rows with reservations grows, the extra space required by this grouping grows linearly alongside it. Therefore, simplifying this storage requirement yields an overall auxiliary space complexity of Big O of R.

Edge Cases

No seats are reserved in any row
How to Handle:
Assume all rows are completely empty and allocate the maximum possible two groups per row.
All seats in every row are reserved
How to Handle:
Track reserved seats in a hash map and contribute zero seated families for those rows.
Rows with no reserved seats present in the input list
How to Handle:
Calculate these unmentioned rows directly using the default maximum of two families per row.
Reserved seats overlap across multiple target blocks (2-5, 4-7, 6-9)
How to Handle:
Check each block independently or use bitmask logic to correctly evaluate overlapping availability.
Extremely large number of rows (up to 10 to the power of 9)
How to Handle:
Store only rows with reservations in a hash map to avoid memory limit issues and iterate efficiently.
Reserved seats located only in columns 1 and 10
How to Handle:
Ignore column 1 and 10 reservations since they do not intersect with any family seating blocks.
Only a single family group fits due to a reservation in the middle column 5 or 6
How to Handle:
Evaluate blocks 2-5, 4-7, and 6-9 separately to ensure the overlapping middle reservation permits at most one group.
Duplicate seat reservations for the same row and seat number in the input list
How to Handle:
Use a set data structure per row to automatically filter out duplicate reservation entries.
0/13 completed