#1845
Seat Reservation Manager
MediumDesignHeap (Priority Queue)HeapPriority Queue
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(log n)Space O(n)
Using a min-heap (priority queue) allows us to efficiently manage the available seats. We can quickly fetch the smallest available seat and also efficiently unreserve seats.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a min-heap to keep track of available seats.
- 2Step 2: For the reserve() method, pop the smallest seat from the heap, mark it as reserved, and return its number.
- 3Step 3: For the unreserve(seatNumber) method, push the seat number back into the heap to mark it as available.
solution.py12 lines
1import heapq
2
3class SeatManager:
4 def __init__(self, n: int):
5 self.available_seats = list(range(1, n + 1))
6 heapq.heapify(self.available_seats)
7
8 def reserve(self) -> int:
9 return heapq.heappop(self.available_seats)
10
11 def unreserve(self, seatNumber: int) -> None:
12 heapq.heappush(self.available_seats, seatNumber)ℹ
Complexity note: The time complexity is O(log n) for both reserve and unreserve operations due to the heap operations. The space complexity is O(n) for storing the seats in the heap.
- 1Using a priority queue allows for efficient seat management.
- 2Min-heaps are ideal for problems requiring frequent access to the smallest element.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.