Seat Reservation Manager - Problem

Design a system that manages the reservation state of n seats that are numbered from 1 to n.

Implement the SeatManager class:

  • SeatManager(int n) Initializes a SeatManager object that will manage n seats numbered from 1 to n. All seats are initially available.
  • int reserve() Fetches the smallest-numbered unreserved seat, reserves it, and returns its number.
  • void unreserve(int seatNumber) Unreserves the seat with the given seatNumber.

Input & Output

Example 1 — Basic Operations
$ Input: operations = ["SeatManager", "reserve", "reserve", "unreserve", "reserve"], values = [[5], [], [], [2], []]
Output: [null, 1, 2, null, 1]
💡 Note: Initialize with 5 seats (1-5 available). reserve() returns 1 (smallest). reserve() returns 2. unreserve(2) makes seat 2 available. reserve() returns 1 (seat 2 is available but 1 < 2).
Example 2 — Multiple Unreserve
$ Input: operations = ["SeatManager", "reserve", "reserve", "unreserve", "unreserve", "reserve"], values = [[3], [], [], [1], [2], []]
Output: [null, 1, 2, null, null, 1]
💡 Note: Initialize with 3 seats. Reserve seats 1 and 2. Unreserve both seats 1 and 2. Next reserve() returns 1 (smaller than 2).
Example 3 — Edge Case with Single Seat
$ Input: operations = ["SeatManager", "reserve", "unreserve", "reserve"], values = [[1], [], [1], []]
Output: [null, 1, null, 1]
💡 Note: Only 1 seat available. Reserve it (returns 1), unreserve it, reserve again (returns 1).

Constraints

  • 1 ≤ n ≤ 105
  • 1 ≤ seatNumber ≤ n
  • At most 105 calls will be made to reserve and unreserve

Visualization

Tap to expand
Seat Reservation Manager: Always Return Smallest AvailableInitial State (n=5):12345All AvailableAfter reserve(), reserve():12345Reserved: 1,2After unreserve(2):12345Available: 2,3,4,5Operations Result:reserve() → 1 (smallest)reserve() → 2 (next smallest)unreserve(2) → nullreserve() → 1 ❌Seat 1 still reserved!reserve() → 2 ✓Seat 2 was unreservedOutput: [null,1,2,null,2]
Understanding the Visualization
1
Input
Initialize with n=5 seats, then reserve, reserve, unreserve(2), reserve
2
Process
Track available seats and always return the smallest number
3
Output
[null,1,2,null,1] - operations return smallest available seat
Key Takeaway
🎯 Key Insight: Use a min-heap to efficiently track and retrieve the smallest available seat number
Asked in
Amazon 15 Google 8 Microsoft 6
28.0K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen