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 seats n.
  • int seat() Returns the label of the seat at which the next student will sit.
  • void leave(int p) Indicates that the student sitting at seat p will leave the room. It is guaranteed that there will be a student sitting at seat p.

Input & Output

Example 1 — Basic Operations
$ Input: ExamRoom(10), seat(), seat(), seat(), seat(), leave(4), seat()
Output: [null,0,9,4,2,null,5]
💡 Note: Initialize room with 10 seats. First student sits at 0. Second at 9 (farthest from 0). Third at 4 (middle of 0-9). Fourth at 2 (middle of 0-4). Remove student at 4. Next student sits at 5 (middle of 2-9).
Example 2 — Small Room
$ Input: ExamRoom(3), seat(), seat(), seat()
Output: [null,0,2,1]
💡 Note: Room has 3 seats. First at 0, second at 2 (end), third at 1 (middle).
Example 3 — Leave and Reseat
$ Input: ExamRoom(5), seat(), seat(), leave(0), seat()
Output: [null,0,4,null,0]
💡 Note: First at 0, second at 4. Remove 0. Next student sits at 0 again (farthest from 4).

Constraints

  • 1 ≤ n ≤ 109
  • It is guaranteed that there will be a student sitting at seat p when leave(p) is called.
  • At most 104 calls will be made to seat and leave.

Visualization

Tap to expand
Exam Room: Maximize Distance StrategyStep 1: Empty RoomStep 2: First Student (seat 0)0Step 3: Second Student (seat 4)04Distance = 4Algorithm:1. If room empty → sit at 02. Find all empty seats3. Calculate distance to nearest occupied4. Choose seat with max distance5. If tied → pick lowest indexRed: Occupied, Gray: Empty, Green: Next Student
Understanding the Visualization
1
Empty Room
Start with n seats, all empty
2
First Student
Always sits at seat 0 when room is empty
3
Maximize Distance
Each new student sits to maximize distance to nearest person
Key Takeaway
🎯 Key Insight: Track occupied seats and find the position that maximizes distance to the closest person
Asked in
Google 15 Facebook 8
67.0K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen