Seat Reservation Manager - Problem
You're tasked with designing a smart seating system for a modern theater or event venue. The system manages n seats numbered from 1 to n, and must efficiently handle two main operations:
- Reserve a seat: Always assign the lowest-numbered available seat to maintain optimal seating arrangement
- Cancel a reservation: Free up a specific seat so it becomes available again
Your SeatManager class should implement:
SeatManager(int n)- Initialize the system withnseats (all initially available)int reserve()- Find and reserve the smallest-numbered unreserved seat, return its numbervoid unreserve(int seatNumber)- Make the specified seat available again
Goal: Design an efficient system that can handle thousands of reservations and cancellations while always maintaining the "lowest available seat first" policy.
Input & Output
example_1.py — Basic Operations
$
Input:
SeatManager(5)
reserve() → 1
reserve() → 2
unreserve(2)
reserve() → 2
›
Output:
1
2
2
💡 Note:
Initialize with 5 seats. First reserve() returns seat 1, second returns seat 2. After unreserving seat 2, next reserve() returns seat 2 again (lowest available).
example_2.py — Multiple Unreservations
$
Input:
SeatManager(3)
reserve() → 1
reserve() → 2
reserve() → 3
unreserve(1)
unreserve(3)
reserve() → 1
›
Output:
1
2
3
1
💡 Note:
Reserve all 3 seats, then unreserve seats 1 and 3. Next reserve() returns seat 1 (smaller than seat 3).
example_3.py — Large Venue
$
Input:
SeatManager(100000)
reserve() → 1
unreserve(1)
reserve() → 1
›
Output:
1
1
💡 Note:
Even with 100,000 seats, operations remain efficient. Reserve seat 1, unreserve it, then reserve again gets seat 1.
Visualization
Tap to expand
Understanding the Visualization
1
Setup
Initialize with all seats available in min-heap
2
Customer Arrives
Extract minimum seat number from heap top
3
Cancellation
Add returned seat back to heap
4
Next Customer
Heap automatically provides next lowest seat
Key Takeaway
🎯 Key Insight: Min-heap provides the perfect balance of efficiency and simplicity, automatically maintaining the "smallest available first" property while delivering O(log n) performance for both operations.
Time & Space Complexity
Time Complexity
O(log n)
Heap operations (extract-min and insert) both take O(log n) time
⚡ Linearithmic
Space Complexity
O(n)
Heap stores all available seats, up to n seats in worst case
⚡ Linearithmic Space
Constraints
- 1 ≤ n ≤ 105
- 1 ≤ seatNumber ≤ n
- For each call to reserve(), it is guaranteed that there will be at least one unreserved seat
- For each call to unreserve(), it is guaranteed that seatNumber will be reserved
- At most 105 calls in total will be made to reserve() and unreserve()
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code