Problem Description
Design a system to simulate an exam room with n seats in a single row (indexed 0 to n-1). When a student enters the room, they choose a seat that maximizes the distance to the closest person (choosing the lowest-indexed seat in case of ties). If the room is empty, the student sits at seat 0. Additionally, implement a method for a student to leave their seat.
Key Insights
- The main challenge is quickly finding the optimal seat on each call of seat() while maintaining the ordered structure of occupied seats.
- Using an ordered container (like a TreeSet or sorted list) allows efficient identification of adjacent seated students.
- The maximum distance could occur at the beginning (seat 0), at the end (seat n-1), or between two occupied seats. For the middle case, the optimal seat is the midpoint.
- When a student leaves, simply remove the seat from the ordered container.
Space and Time Complexity
Time Complexity: O(m) per seat() or leave() call in worst case, where m is the number of occupied seats (with m up to O(10^4)).
Space Complexity: O(m), as we store the occupied seats.
Solution
We maintain a sorted list (or equivalent ordered set in other languages) to keep track of occupied seats. For seat():
- If the room is empty, return seat 0.
- Otherwise, calculate the distance from 0 to the first occupied seat and from the last occupied seat to n - 1.
- For every pair of adjacent occupied seats, compute the distance as half the gap.
- Select the position that gives the maximum distance to the nearest student; if multiple positions yield the same distance, choose the smallest seat number.
- Insert the seat into the sorted list.
For leave(p):
- Remove p from the sorted list.
- No merging of intervals is explicitly needed since the sorted list always reflects the current seating arrangement.
This approach leverages ordered data structures and scanning of adjacent elements to always find the best seat efficiently.