LeetCode Problem 855: Exam Room
In an exam room with N
seats, each seat is consecutively numbered from 0
to N-1
. When a student enters the room, they should sit down in a seat such that the distance to the closest person is maximized. If there are multiple seats with the same maximum distance, they sit in the seat with the lowest number. If no one is in the room, the student sits at seat number 0
.
Implement the ExamRoom
class:
ExamRoom(int N)
Initializes the object with N
seats.int seat()
Returns the seat number where the next student will sit.void leave(int p)
Indicates that the student in seat p
has left the room.Example:
ExamRoom examRoom = new ExamRoom(10);
cout << examRoom.seat(); // returns 0
cout << examRoom.seat(); // returns 9
cout << examRoom.seat(); // returns 4
cout << examRoom.seat(); // returns 2
examRoom.leave(4);
cout << examRoom.seat(); // returns 5
Constraints:
seat
and leave
will be called at most 10^4
times across all test cases.We need a data structure to efficiently manage and query the current seat occupancy. A possible choice is a set
to store the currently occupied seat numbers since it provides efficient insertion, deletion, and lookup.
seat()
is called:
0
.leave(int p)
is called:
p
from the data structure.set
, which supports log(n) operations for inserting and deleting seats.#include <set>
#include <iostream>
using namespace std;
class ExamRoom {
private:
set<int> seats;
int N;
public:
ExamRoom(int N) : N(N) {}
int seat() {
if (seats.empty()) {
seats.insert(0);
return 0;
}
// Find the position to sit.
int maxDist = *seats.begin(); // Check the first position
int prev = -1;
int seat = 0;
for(auto it = seats.begin(); it != seats.end(); it++) {
if (prev != -1) {
int dist = (*it - prev) / 2;
if (dist > maxDist) {
maxDist = dist;
seat = prev + dist;
}
}
prev = *it;
}
// Check the last position
if (N - 1 - *seats.rbegin() > maxDist) {
seat = N - 1;
}
seats.insert(seat);
return seat;
}
void leave(int p) {
seats.erase(p);
}
};
int main() {
ExamRoom examRoom(10);
cout << examRoom.seat() << endl; // returns 0
cout << examRoom.seat() << endl; // returns 9
cout << examRoom.seat() << endl; // returns 4
cout << examRoom.seat() << endl; // returns 2
examRoom.leave(4);
cout << examRoom.seat() << endl; // returns 5
return 0;
}
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?