885. Exam Room
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to design a class ExamRoom that manages seating for students in a single row of n seats, labeled 0 to n-1. The core logic revolves around two operations: seat() and leave().
Solution
Exam Room in Python
import bisect
class ExamRoom:
def __init__(self, n: int):
self.n = n
self.students = []
def seat(self) -> int:
# If no students are in the room, sit at seat 0.
if not self.students:
self.students.append(0)
return 0
# Find the seat that maximizes the distance to the closest person.
# Initialize with the case of sitting at seat 0.
# The distance is to the first student.
max_dist = self.students[0]
best_seat = 0
# Iterate through adjacent students to find the largest gap.
for i in range(len(self.students) - 1):
p, q = self.students[i], self.students[i+1]
dist = (q - p) // 2
# If we find a larger gap, update max_dist and best_seat.
# The tie-breaking rule (lower seat number) is naturally handled
# by only updating for strictly greater distances.
if dist > max_dist:
max_dist = dist
best_seat = p + dist
# Consider the case of sitting at seat n-1.
# The distance is from the last student.
dist_at_end = (self.n - 1) - self.students[-1]
if dist_at_end > max_dist:
best_seat = self.n - 1
# Insert the new student's seat into the sorted list.
bisect.insort(self.students, best_seat)
return best_seat
def leave(self, p: int) -> None:
# Remove student at seat p. It's guaranteed to exist.
self.students.remove(p)
Exam Room in Java
class ExamRoom {
private int n;
private List<Integer> students;
public ExamRoom(int n) {
this.n = n;
this.students = new ArrayList<>();
}
public int seat() {
// If no students are in the room, sit at seat 0.
if (students.isEmpty()) {
students.add(0);
return 0;
}
// Find the seat that maximizes the distance to the closest person.
// Initialize with the case of sitting at seat 0.
// The distance is to the first student.
int maxDist = students.get(0);
int bestSeat = 0;
// Iterate through adjacent students to find the largest gap.
for (int i = 0; i < students.size() - 1; i++) {
int p = students.get(i);
int q = students.get(i + 1);
int dist = (q - p) / 2;
// If we find a larger gap, update maxDist and bestSeat.
// The tie-breaking rule (lower seat number) is naturally handled
// by only updating for strictly greater distances.
if (dist > maxDist) {
maxDist = dist;
bestSeat = p + dist;
}
}
// Consider the case of sitting at seat n-1.
// The distance is from the last student.
int distAtEnd = (n - 1) - students.get(students.size() - 1);
if (distAtEnd > maxDist) {
bestSeat = n - 1;
}
// Insert the new student's seat into the sorted list.
// Collections.binarySearch finds the insertion point.
int insertionPoint = Collections.binarySearch(students, bestSeat);
if (insertionPoint < 0) {
insertionPoint = -(insertionPoint + 1);
}
students.add(insertionPoint, bestSeat);
return bestSeat;
}
public void leave(int p) {
// Remove student at seat p. It's guaranteed to exist.
students.remove(Integer.valueOf(p));
}
}
Exam Room in C++
class ExamRoom {
private:
int n;
std::vector<int> students;
public:
ExamRoom(int n) : n(n) {}
int seat() {
// If no students are in the room, sit at seat 0.
if (students.empty()) {
students.push_back(0);
return 0;
}
// Find the seat that maximizes the distance to the closest person.
// Initialize with the case of sitting at seat 0.
// The distance is to the first student.
int maxDist = students[0];
int bestSeat = 0;
// Iterate through adjacent students to find the largest gap.
for (size_t i = 0; i < students.size() - 1; ++i) {
int p = students[i];
int q = students[i+1];
int dist = (q - p) / 2;
// If we find a larger gap, update maxDist and bestSeat.
// The tie-breaking rule (lower seat number) is naturally handled
// by only updating for strictly greater distances.
if (dist > maxDist) {
maxDist = dist;
bestSeat = p + dist;
}
}
// Consider the case of sitting at seat n-1.
// The distance is from the last student.
int distAtEnd = (n - 1) - students.back();
if (distAtEnd > maxDist) {
bestSeat = n - 1;
}
// Insert the new student's seat into the sorted list.
// std::lower_bound finds the first element not less than bestSeat.
auto it = std::lower_bound(students.begin(), students.end(), bestSeat);
students.insert(it, bestSeat);
return bestSeat;
}
void leave(int p) {
// Find the student to remove. It's guaranteed to exist.
// std::lower_bound finds the position of p in O(log k) time.
auto it = std::lower_bound(students.begin(), students.end(), p);
// std::vector::erase takes O(k) time.
if (it != students.end() && *it == p) {
students.erase(it);
}
}
};
Exam Room in TypeScript
class ExamRoom {
private n: number;
private students: number[];
constructor(n: number) {
this.n = n;
this.students = [];
}
seat(): number {
// If no students are in the room, sit at seat 0.
if (this.students.length === 0) {
this.students.push(0);
return 0;
}
// Find the seat that maximizes the distance to the closest person.
// Initialize with the case of sitting at seat 0.
// The distance is to the first student.
let maxDist = this.students[0];
let bestSeat = 0;
// Iterate through adjacent students to find the largest gap.
for (let i = 0; i < this.students.length - 1; i++) {
const p = this.students[i];
const q = this.students[i+1];
const dist = Math.floor((q - p) / 2);
// If we find a larger gap, update maxDist and bestSeat.
// The tie-breaking rule (lower seat number) is naturally handled
// by only updating for strictly greater distances.
if (dist > maxDist) {
maxDist = dist;
bestSeat = p + dist;
}
}
// Consider the case of sitting at seat n-1.
// The distance is from the last student.
const distAtEnd = (this.n - 1) - this.students[this.students.length - 1];
if (distAtEnd > maxDist) {
bestSeat = this.n - 1;
}
// Insert the new student's seat into the sorted list.
// Find insertion point to maintain sorted order.
let insertionPoint = this.students.findIndex(s => s > bestSeat);
if (insertionPoint === -1) {
this.students.push(bestSeat);
} else {
this.students.splice(insertionPoint, 0, bestSeat);
}
return bestSeat;
}
leave(p: number): void {
// Remove student at seat p. It's guaranteed to exist.
const index = this.students.indexOf(p);
if (index > -1) {
this.students.splice(index, 1);
}
}
}
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.