Cinema Seat Allocation — LeetCode 1386 Python Solution

MediumGreedyBit ManipulationArrayHash Table
Problem
#1386
Reading time
3 min

The problem

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.

Example

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.

Python solution

Python
class Solution:
    def maxNumberOfFamilies(self, n: int, reservedSeats: List[List[int]]) -> int:
        d = defaultdict(int)
        for i, j in reservedSeats:
            d[i] |= 1 << (10 - j)
        masks = (0b0111100000, 0b0000011110, 0b0001111000)
        ans = (n - len(d)) * 2
        for x in d.values():
            for mask in masks:
                if (x & mask) == 0:
                    x |= mask
                    ans += 1
        return ans

Complexity

MeasureComplexity
TimeO(m)
SpaceO(m) auxiliary

Pattern: Bit Manipulation

Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 1386. Cinema Seat Allocation is filed here because LeetCode tags it Bit Manipulation, which is the vocabulary this hub collects.

The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1386. Cinema Seat Allocation?
LeetCode 1386. Cinema Seat Allocation is rated Medium on LeetCode.
What is the time complexity of LeetCode 1386. Cinema Seat Allocation?
The Python solution on this page runs in O(m).
What is the space complexity of LeetCode 1386. Cinema Seat Allocation?
The Python solution on this page uses O(m) auxiliary space.
What topics does LeetCode 1386. Cinema Seat Allocation cover?
LeetCode 1386. Cinema Seat Allocation is tagged Greedy, Bit Manipulation, Array and Hash Table on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview