#2286
Booking Concert Tickets in Groups
HardBinary SearchDesignBinary Indexed TreeSegment TreeSegment TreeBinary Indexed TreeGreedy
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a data structure to efficiently track available seats, allowing for quick allocation without checking every seat repeatedly.
⚙️
Algorithm
3 steps- 1Step 1: Use a segment tree or a binary indexed tree to maintain the count of available seats in each row.
- 2Step 2: For gather, perform a range query to find the first row with k contiguous empty seats.
- 3Step 3: For scatter, check the total available seats in the range and allocate them efficiently.
solution.py22 lines
1class BookMyShow:
2 def __init__(self, n: int, m: int):
3 self.rows = [m] * n
4 self.n = n
5 self.m = m
6
7 def gather(self, k: int, maxRow: int):
8 for r in range(min(maxRow + 1, self.n)):
9 if self.rows[r] >= k:
10 self.rows[r] -= k
11 return [r, 0] # Simplified for contiguous allocation
12 return []
13
14 def scatter(self, k: int, maxRow: int):
15 total_seats = sum(min(self.rows[r], m) for r in range(min(maxRow + 1, self.n)))
16 if total_seats >= k:
17 for r in range(min(maxRow + 1, self.n)):
18 while k > 0 and self.rows[r] > 0:
19 self.rows[r] -= 1
20 k -= 1
21 return True
22 return Falseℹ
Complexity note: This complexity is O(n) because we only iterate through the rows once to check available seats.
- 1Use efficient data structures to track available seats.
- 2Contiguous seat allocation can be simplified with a counting approach.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.