Problem Description
Design a system that manages the reservation state of n seats numbered from 1 to n. The system should support reserving the smallest-numbered available seat and unreserving a seat by its number.
Key Insights
- Use a min-heap (priority queue) to efficiently track the smallest available seat.
- On initialization, push all seats (from 1 to n) into the heap.
- Reserving involves popping the minimum element, which guarantees the smallest available seat.
- Unreserving involves pushing the seat number back onto the heap.
- Both reserve and unreserve operations run in O(log n) time.
Space and Time Complexity
Time Complexity:
- reserve: O(log n)
- unreserve: O(log n)
Space Complexity: O(n) because we keep all seat numbers in a min-heap.
Solution
We maintain a min-heap to store all currently available seat numbers. Initially, all seats (1 to n) are available, so we push all of them into the heap. When a reserve() call is made, the smallest available seat is popped from the heap and returned as reserved. Conversely, when unreserve(seatNumber) is called, the seat number is pushed back into the heap to mark it as available again. This structure ensures that both operations perform efficiently under the given constraints.
Code Solutions
Below are the implementations in Python, JavaScript, C++, and Java.