Problem
A concert hall has n
rows numbered from 0
to n - 1
, each with m
seats, numbered from 0
to m - 1
. You need to design a ticketing system that can allocate seats in the following cases:
- If a group of
k
spectators can sit together in a row. - If every member of a group of
k
spectators can get a seat. They may or may not sit together.
Note that the spectators are very picky. Hence:
- They will book seats only if each member of their group can get a seat with row number less than or equal to
maxRow
.maxRow
can vary from group to group. - In case there are multiple rows to choose from, the row with the smallest number is chosen. If there are multiple seats to choose in the same row, the seat with the smallest number is chosen.
Implement the BookMyShow
class:
BookMyShow(int n, int m)
Initializes the object withn
as number of rows andm
as number of seats per row.int[] gather(int k, int maxRow)
Returns an array of length2
denoting the row and seat number (respectively) of the first seat being allocated to thek
members of the group, who must sit together. In other words, it returns the smallest possibler
andc
such that all[c, c + k - 1]
seats are valid and empty in rowr
, andr <= maxRow
. Returns[]
in case it is not possible to allocate seats to the group.boolean scatter(int k, int maxRow)
Returnstrue
if allk
members of the group can be allocated seats in rows0
tomaxRow
, who may or may not sit together. If the seats can be allocated, it allocatesk
seats to the group with the smallest row numbers, and the smallest possible seat numbers in each row. Otherwise, returnsfalse
.
Examples
Example 1
|
|
Constraints
1 <= n <= 5 * 10^4
1 <= m, k <= 10^9
0 <= maxRow <= n - 1
- At most
5 * 10^4
calls in total will be made togather
andscatter
.
Solution
Method 1 – Segment Tree for Range Maximum and Sum
Intuition
To efficiently support group bookings (together or scattered) and queries for available seats, we use a segment tree to maintain the maximum and sum of available seats in each row. This allows us to quickly find the first row with enough seats and update seat counts after booking.
Approach
- Build a segment tree where each node stores the maximum and sum of available seats in its range.
- For
gather(k, maxRow)
, find the first row ≤ maxRow with at least k consecutive seats, allocate them, and update the tree. - For
scatter(k, maxRow)
, check if the total available seats in rows ≤ maxRow is at least k, then allocate seats greedily from the lowest row and update the tree. - Both operations run in O(log n) time per query.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(log n)
per query for segment tree,O(n)
for simple array (Python version). - 🧺 Space complexity:
O(n)
— For seat tracking arrays.