1386. Cinema Seat Allocation
Description
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^91 <=ย reservedSeats.length <= min(10*n, 10^4)reservedSeats[i].length == 21ย <=ย reservedSeats[i][0] <= n1 <=ย reservedSeats[i][1] <= 10- All
reservedSeats[i]are distinct.
Solutions
Solution 1: Hash Table + Bit Manipulation
We use a hash table \(d\) to store all the reserved seats, where the key is the row number, and the value is the state of the reserved seats in that row, i.e., a binary number. The \(j\)-th bit being \(1\) means the \(j\)-th seat is reserved, and \(0\) means the \(j\)-th seat is not reserved.
We traverse \(reservedSeats\), for each seat \((i, j)\), we add the state of the \(j\)-th seat (corresponding to the \(10-j\) bit in the lower bits) to \(d[i]\).
For rows that do not appear in the hash table \(d\), we can arrange \(2\) families arbitrarily, so the initial answer is \((n - len(d)) \times 2\).
Next, we traverse the state of each row in the hash table. For each row, we try to arrange the situations \(1234, 5678, 3456\) in turn. If a situation can be arranged, we add \(1\) to the answer.
After the traversal, we get the final answer.
The time complexity is \(O(m)\), and the space complexity is \(O(m)\). Where \(m\) is the length of \(reservedSeats\).
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |

