Leetcode 1845: Seat Reservation Manager

grid47
grid47
Exploring patterns and algorithms
May 6, 2024 6 min read

Design a system to manage the reservation state of n seats numbered from 1 to n. Implement the SeatManager class to handle reserving and unreserving seats. The class should be able to return the smallest available seat when reserved, and make seats available again when unreserved.
Problem
Approach
Steps
Complexity
Input: You are given an integer n, which represents the number of seats. The operations are called as a sequence of commands where reserve() reserves the smallest available seat and unreserve(seatNumber) unreserves a seat.
Example: [5], [], [], [2], [], [], [], [], [5]
Constraints:
• 1 <= n <= 10^5
• 1 <= seatNumber <= n
• At least one unreserved seat will be available for each reserve call.
• seatNumber will always refer to a reserved seat for each unreserve call.
Output: For each call to reserve, return the smallest available seat number. For each call to unreserve, no return value is expected, but the seat is made available again.
Example: [null, 1, 2, null, 2, 3, 4, 5, null]
Constraints:
Goal: The system should efficiently handle reserving and unreserving seats while keeping track of the smallest available seat number.
Steps:
• Use a priority queue to keep track of available seats.
• Initialize the seats from 1 to n, making them all available initially.
• On calling reserve(), pop the smallest seat from the queue.
• On calling unreserve(), push the seat back into the priority queue.
Goal: The input will always guarantee that there is at least one available seat for reserve calls, and the seatNumber for unreserve will always refer to a seat that has been reserved.
Steps:
• 1 <= n <= 10^5
• 1 <= seatNumber <= n
Assumptions:
• The SeatManager class is initialized correctly with n seats.
• The input operations are valid according to the problem constraints.
Input: [5], [], [], [2], [], [], [], [], [5]
Explanation: The SeatManager starts with 5 seats. After reserving and unreserving as per the sequence, the smallest available seats are allocated, and seats are made available again after unreserving.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus