Leetcode 855: Exam Room

grid47
grid47
Exploring patterns and algorithms
Aug 13, 2024 7 min read

You are tasked with simulating an exam room where students will choose seats based on a strategy that maximizes their distance from the closest person already seated. If multiple seats have the same distance, the student will choose the seat with the smallest index. Additionally, students can leave the room, freeing up their seats.
Problem
Approach
Steps
Complexity
Input: The input consists of an integer n, which represents the number of seats in the exam room. The object should allow for two operations: seating a student and having a student leave a seat.
Example: Input: ["ExamRoom", "seat", "seat", "seat", "seat", "leave", "seat"] [[10], [], [], [], [], [4], []]
Constraints:
• 1 <= n <= 10^9
• At most 10^4 calls will be made to the 'seat' and 'leave' operations.
Output: For each 'seat' operation, return the seat index where the student will sit. For the 'leave' operation, there is no return value.
Example: Output: [null, 0, 9, 4, 2, null, 5]
Constraints:
Goal: To implement the seating strategy such that students sit at the seat that maximizes the distance from the nearest student. If there are multiple options, choose the smallest seat index.
Steps:
• Step 1: Implement a data structure to track the positions of students already seated.
• Step 2: For each 'seat' operation, calculate the maximum distance to the nearest student for each empty seat and choose the seat that maximizes this distance.
• Step 3: For each 'leave' operation, remove the seat from the list of occupied seats.
Goal: Ensure efficient handling of the seating strategy given that the number of seats n can be very large.
Steps:
• Seats are indexed from 0 to n-1, and each student occupies a unique seat at a time.
Assumptions:
• There will always be at least one seat available when a student arrives.
Input: Input: ["ExamRoom", "seat", "seat", "seat", "seat", "leave", "seat"] [[10], [], [], [], [], [4], []]
Explanation: Initially, no student is seated. The first student sits at seat 0. The next student sits at the farthest available seat, seat 9. The next one sits at seat 4 (the middle of the remaining seats). The next student sits at seat 2. When the student at seat 4 leaves, the next student sits at seat 5 (the next best available seat).

Link to LeetCode Lab


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