#1386

Cinema Seat Allocation

Medium
ArrayHash TableGreedyBit ManipulationHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a greedy approach to maximize the number of four-person groups by checking the reserved seats in each row and determining the best possible allocation for two families per row.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a set to track reserved seats.
  2. 2Step 2: For each row, check the reserved seats and determine how many groups can be formed based on the available seats.
  3. 3Step 3: Use conditions to check for the three possible configurations of groups in a row and count them accordingly.
solution.py15 lines
1# Full working Python code
2class Solution:
3    def maxNumberOfFamilies(self, n: int, reservedSeats: List[List[int]]) -> int:
4        reserved = set((r, s) for r, s in reservedSeats)
5        total_groups = 0
6        for row in range(1, n + 1):
7            groups = 0
8            if (row, 2) not in reserved and (row, 3) not in reserved and (row, 4) not in reserved and (row, 5) not in reserved:
9                groups += 1
10            if (row, 6) not in reserved and (row, 7) not in reserved and (row, 8) not in reserved and (row, 9) not in reserved:
11                groups += 1
12            if (row, 4) not in reserved and (row, 5) not in reserved and (row, 6) not in reserved and (row, 7) not in reserved:
13                groups += 1
14            total_groups += groups
15        return total_groups

Complexity note: This complexity is linear because we only iterate through the reserved seats and check each row once, making it efficient even for larger inputs.

  • 1Understanding how to maximize the number of groups by checking configurations is crucial.
  • 2Using a set to track reserved seats allows for O(1) lookups, making the solution efficient.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.