Exam Room - Solution & Explanation
Problem Statement
There is an exam room with n seats in a single row labeled from 0 to n - 1.
When a student enters the room, they must sit in the seat that maximizes the distance to the closest person. If there are multiple such seats, they sit in the seat with the lowest number. If no one is in the room, then the student sits at seat number 0.
Design a class that simulates the mentioned exam room.
Implement the ExamRoom class:
ExamRoom(int n)Initializes the object of the exam room with the number of the seatsn.int seat()Returns the label of the seat at which the next student will set.void leave(int p)Indicates that the student sitting at seatpwill leave the room. It is guaranteed that there will be a student sitting at seatp.
Example 1:
Input ["ExamRoom", "seat", "seat", "seat", "seat", "leave", "seat"] [[10], [], [], [], [], [4], []] Output [null, 0, 9, 4, 2, null, 5] Explanation ExamRoom examRoom = new ExamRoom(10); examRoom.seat(); // return 0, no one is in the room, then the student sits at seat number 0. examRoom.seat(); // return 9, the student sits at the last seat number 9. examRoom.seat(); // return 4, the student sits at the last seat number 4. examRoom.seat(); // return 2, the student sits at the last seat number 2. examRoom.leave(4); examRoom.seat(); // return 5, the student sits at the last seat number 5.
Constraints:
1 <= n <= 109- It is guaranteed that there is a student sitting at seat
p. - At most
104calls will be made toseatandleave.
Approach Overview
Problem Overview: You manage an exam room with n seats numbered 0 to n-1. Each arriving student chooses a seat that maximizes the distance to the closest occupied seat. If multiple seats give the same distance, the student picks the smallest index. You must implement seat() and leave(p) efficiently.
Approach 1: Sorted List of Occupied Seats (O(n) seat, O(n) leave)
This approach maintains a sorted list (or ordered set) of occupied seat indices. When a student calls seat(), iterate through the sorted seats and compute the largest possible distance between adjacent occupied seats. Also check the edges: the distance from seat 0 to the first student and from the last student to n-1. The best candidate seat is either the midpoint between two occupied seats or an edge seat. Insert the chosen seat into the sorted structure and maintain order.
The key idea is that the optimal seat always lies either at the midpoint of the largest gap or at a boundary. Computing the midpoint of each gap requires scanning the occupied list, which takes O(n) time. Insertion or deletion in a list also costs O(n). Space complexity is O(n) because you store all occupied seats. This approach is straightforward and easy to implement, especially in Python with a list or in C++ with an ordered container from Ordered Set.
Approach 2: Maximum Heap of Intervals (O(log n) seat, O(log n) leave)
A more scalable design models the room as intervals of empty seats. Each interval represents the gap between two occupied seats, such as (left, right). The best seat inside an interval is the midpoint that maximizes the distance to neighbors. Store intervals in a max heap ordered by their effective seating distance (largest first), with ties broken by smaller seat index.
When seat() runs, extract the largest interval from the heap. Compute the optimal seat inside it, then split the interval into two new intervals and push them back into the heap. When leave(p) runs, merge the two intervals adjacent to seat p into a larger interval and update the heap. Efficient merging usually requires hash maps that track interval boundaries.
This design relies on a Heap (Priority Queue) to always retrieve the largest gap in O(log n) time. Both seating and leaving operations maintain interval structure with heap updates. Space complexity remains O(n). The approach demonstrates strong Design skills because you model the room as dynamic segments rather than raw seat indices.
Recommended for interviews: Start by explaining the sorted list approach to show the greedy insight that students always sit in the largest gap. Then present the interval heap design as the optimized solution. Interviewers typically expect the heap-based design because it reduces repeated scans and keeps operations near O(log n), which scales well when many seat and leave operations occur.
Approach 1: Approach 1: Sorted List of Occupied Seats
This approach uses a sorted list to keep track of occupied seats. When a student enters the room, we calculate potential distances at each interval and choose the seat that maximizes the minimum distance to any occupied seat. If multiple seats provide the same distance, the earliest seat in terms of index is chosen. When a student leaves, we simply remove the seat from the list.
We maintain a sorted list of occupied seats, allowing us to compute potential seating distances dynamically. The bisect module helps insert the new student in a sorted manner. Distances are checked between each successive occupied seat, including the boundaries.
Complexity
The time complexity is O(N) for the seat method, where N is the number of currently occupied seats. The leave method has a time complexity of O(N) due to list manipulation. The space complexity is O(N) for storing the list of occupied seats.
Approach 2: Approach 2: Maximum Heap of Intervals
In this approach, we utilize a max-heap (priority queue) to manage seat intervals. Each interval is prioritized by its distance, allowing us to efficiently determine where to seat the next student. The order of seating follows the priority determined by the maximum possible distance in the available intervals. When a student leaves, the adjacent intervals are merged and updated in the heap.
In this Java implementation, a priority queue manages intervals defined by two endpoints. The queue is structured such that intervals with the largest possible seating distances are dequeued first. When a new student is seated, two new intervals are created based on the seated position. The priority queue allows efficient management of these operations.
Code
Java
JavaScript
Complexity
Both seat and leave methods have a time complexity of O(logN), where N is the number of intervals in the room. This complexity arises from the operations in the priority queue. Space complexity is O(N), accounting for storing intervals in the queue.
Approach 3: Ordered Set + Hash Table
Considering that each time we call seat(), we need to find the seat with the maximum distance, we can use an ordered set to store seat intervals. Each element of the ordered set is a tuple (l, r), indicating that the seats between l and r (excluding l and r) can be occupied by a student. Initially, the ordered set contains only one element (-1, n), indicating that the seats between (-1, n) can be occupied by a student.
Additionally, we use two hash tables left and right to maintain the left and right neighbors of each occupied seat, making it easier to merge two seat intervals when calling leave(p).
The time complexity is O(log n), and the space complexity is O(n). Here, n is the number of seats in the exam room.
Code
Python
Java
C++
Go
TypeScript
Complexity Comparison
| Approach | Complexity |
|---|---|
| Approach 1: Sorted List of Occupied Seats | The time complexity is O(N) for the seat method, where N is the number of currently occupied seats. The leave method has a time complexity of O(N) due to list manipulation. The space complexity is O(N) for storing the list of occupied seats. |
| Approach 2: Maximum Heap of Intervals | Both |
| Ordered Set + Hash Table | — |
Detailed Complexity Analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Sorted List of Occupied Seats | seat(): O(n), leave(): O(n) | O(n) | Good for simple implementations or when the number of operations is small |
| Maximum Heap of Intervals | seat(): O(log n), leave(): O(log n) | O(n) | Best for large numbers of operations; maintains the largest seating gap efficiently |
Video Solution
855. Exam Room (LeetCode) • hakunamatasq • 4,478 views views
Watch 9 more video solutions →Frequently Asked Questions
Is Exam Room easy or hard?
Exam Room Python or Java solution?
How to solve Exam Room in O(log n)?
What is the best approach for Exam Room?
Is Exam Room asked at Google/Amazon/Meta?
What data structure is used in Exam Room?
What is the time complexity of Exam Room?
Ready to solve this problem?
Practice Exam Room with our built-in code editor and test cases.
Practice on FleetCode